Category Archives: ProgrammingTips

Javascript jQuery Organisation ProgrammingTips

jQuery Best Practices- Performance

Published by:

Despite being one of the most popular JavaScript libraries today jQuery has its shortcomings too.

If used carelessly, it can lead to performance issues. This post will list some of the best practices in using jQuery that will help us avoid them.

  1. Limit DOM Interaction 
    There is a cost when manipulating the DOM tree using jquery. So try to limit interaction with the DOM. Lets take a look at the below code:

    Well, no points for guessing whats wrong here. This piece of code works just fine, since the fruits array is of 8 items only. But suppose we had a list of 1000 items, it would really mess up the speed of the website because we are repeatedly appending elements to the DOM, inside a loop.
    Instead of doing this, we can build up a html first and then append it to the DOM.
  2. Handling Events on Selectors
    Though jQuery can select elements very quickly, it is not necessary to search for the same elements many times.

  3. Optimize Selectors
    With the first approach, jQuery queries the DOM using document.querySelectorAll(). With the second, jQuery uses document.getElementById(), which is faster, although the speed improvement may be diminished by the subsequent call to .find().

    Specificity: 
    Be specific on the right-hand side of your selector, and less specific on the left.
  4. Detach Elements to Work with Them
    The DOM is slow; you want to avoid manipulating it as much as possible. jQuery introduced detach()  in version 1.4 to help address this issue, allowing you to remove an element from the DOM while you work with it.
  5. Use Stylesheets for Changing CSS
    If you’re changing the CSS of more than 20 elements using .css(), consider adding a style tag to the page instead for a nearly 60% increase in speed.
  6. Avoid $( window ).load()

    The $( document ).ready() is fired when a page’s own DOM is loaded, but not external assets like images and stylesheets while $( window ).load() is fired when everything a page is made up of, including its own content and its sub-resources are loaded.

    So, if you’re writing a script that relies on a page’s sub-resources, like changing the background color of a div that’s styled by an external stylesheet, only then use $( window ).load() else it’s better to stick to $( document ).ready().

 

Javascript ProgrammingTips

Execute a function within a Directive from outside in AngularJS

Published by:

We were working on two problem statements at different points in time of a project and we interestingly found similar solution for both.

Problem A: We have a form, one of the input fields  (defined as a directive) has a clear button. This clears the text in the input field, the data in the ng-model as well as the data held in the variable that gets submitted finally via the form. Now, we have a universal clear button that also needs to clear all the 3 data points.

Problem B: We have a section that has been defined as a directive which can be expanded/collapsed using a toggle button. The expand/collapse is handled by the directive. The initial state of the directive, whether it should be expanded or collapsed, is actually dependent on a value obtained from an API call.

In both cases the common thing that one can notice is that there is an external trigger that needs to be passed on into the directive. In Angular 1.4 there is no direct way to do this. Directives do support two way binding, and passing initial values. But neither would solve the exact requirement in both problems.

The solution that we came up with was passing a control object to the directive. The controller defined a control object, a key of which will be pointing to a function. This object was passed on to the directive, and directive initialised the control object’s key (control object which is two-way bound) with a function that gives access to the variables/functions inside the directive. Being two-way bound, this function is now available in the controller. This can be passed on to anywhere (factory, as it was in case of solution for problem B) or used locally.

Sample code:

 

ProgrammingTips

Making Aws::SES API to work with ActionMailer

Published by:

Aws::SES SMTP integration is a cake walk indeed. But SES API does not directly work with ActionMailer. I think there could be a better approach but for the current requirement I made it work this way:

1. Added SES as a delivery method:

In initializer, add your SES configuration and add the SES client as  new delivery method:

You have to specify Region as well. I had already added

to my application.yml

2. Asked ActionMailer to use ses delivery method in your environment:

Add the following line to config/environments/<environment>.rb

Once you are done with this you are ready to send mail. Well I also thought the same, but when I ran the code BOOM. So what we dont have is deliver! method in the Aws::SES module. So you extend Aws::SES:Client. I did it in the initializer itself.

3. Added the following code to config/initializer/ses.rb

VOILA! You get back the message ID that the API send back and you can store it to track the delivery status of your mail.

Note: AWS SES provides SMTP service as well, which is easier to integrate but you wont be able to track the deliver from your application. Also SMTP access key pair is different from the access key pair that we use for API (which is global API key pair. I have not tried the IAM setting with this).

Asset Pipeline Development RailsTips

How to figure out Runtime Dependencies when using Bower via Rails Assets

Published by:

Recently, for one of our client projects we decided to make use of Bower via Rails Assets to better manage Javascript dependencies with respect to the application. This project is on Rails 4.0.13 . For reasons as to why we choose this approach one can refer to the below two blogs –

1. Better Asset Management in Rails Using Rails Assets

2. Bower through Rails Assets

In our application, we were basically replacing the existing dependencies(few of which were placed in vendor/assets/javascripts and others were gems like the jquery-ui-rails) with gems provided to us via the Rails Assets site.

One such third party plugin that we had to replace was the jquery validate plugin. After including the appropriate gem(rails-assets-jquery-validate) from rails-assets site in the gemfile and running bundle to install that gem you might observe from the Gemfile.lock that this gem depends on the rails-assets-jquery-gem.

The BIG question now is, how does the rails-assets-jquery-validate gem(I had installed the gem with version 1.13.1) know which version of the rails-assets-jquery gem it should pick up, given that unlike rubygems.org the current rails-assets site(based on the screenshot below) doesn’t currently list the runtime dependencies required for a gem(which in our case is that we can’t directly find the runtime dependencies for rails-assets-jquery-validate gem).

The workaround

One can find out the exact dependencies required wrt a specific gem by checking out the bower.json file with respect to appropriate code repository corresponding to the gem(in the context of our e.g., this would be for checking out the bower.json file of the rails-assets-jquery-validate gem related code repository) listed on the rails assets site.

 

Development ProgrammingTips

Auto redirect based on language in nginx

Published by:

When you want to do an auto redirect based on the AcceptLanguage parameter sent by the browser the first solution that comes up in Google is this:

This will not work because the AcceptLanguage is of the following form:

And Map will always map to the first one and will not respect the priority.

Solution:

Put this in the nginx

make sure you do :

 

RailsTips

Creating Your First Gem is Easy…

Published by:

Many of us used of so many gems in ruby, so lets try to create a basic gem.
Simple, We just have to generate two files to create your own gem.

Step1: Create a gemspec.
Create a gemspec file inside root directory, file-name should be same as your gem name (Eg: In our case its greeting_gem.gemspec)

– Specify your gem specifications

Step2: Add some code.
Create a greeting_gem.rb file in lib folder

Step 3: Generate gem file.

This command will build the gem, which can be used in another ruby program.

Step 4: Test the gem.
gem install greeting_gem, to install the gem locally to test it out.
open irb
>> require ‘greeting_gem’
=> true
>> GreetingGem.greeting(‘sravani’)
Hello sravani

Isn’t it simple!
Add as many methods you want in the same way and move on to bigger things.

ProgrammingTips RailsTips

RailsTip: Setting boolean values in ActiveRecord callbacks

Published by:

I realized the importance of reading documentation clearly and with care, when I spent hours debugging this stupid problem.

This is an Active Record callback in action. We are setting a boolean field ‘approved’ to false in the before_create ActiveRecord callback.

This code is simple, straightforward and looks flawless, until you see a ActiveRecord::RecordNotSaved exception when you try to create a Topic. Our only savior, the errors object also doesn’t give us any information on what went wrong.

Two important things we always forget and aren’t quite obvious are

1. Implicit return values in Ruby. This feature always returns the value of the last executed statement in a method or block.

2. If an ActiveRecord callback returns false, all the later callbacks and the associated action are cancelled.

In our example, the statement ‘self.approved = false’ returns false and since that is the last statement executed in the callback, the callback returns false which cancels the create operation.

So, the best way to set boolean values in an ActiveRecord callback is