Thursday 17 October 2013

Check if jquery plugin is loaded

We might always want jquery plugin which would be used in specific page instead of getting loaded in all pages.  We call that jquery plugin file in that page only and also define the function in particular html page only. But writing this code in particular page is not a good practice instead it should be in written in main javascript file which contains all the jquery functions.

 If we write that function in main javascript file then we end with getting error as that plugin file is been defined in that particluar page only.

 How to check if jquery plugin is loaded or not ?

   
 Checking if method exist

   if($.fn.pluginname != 'undefined'){}


 Shorthand

   if($.fn.pluginname){}


  Replace pluginname with whatever you are calling.

Example:


   if($.fn.accordion){
     $("#accordion").accordion({
       heightStyle: "content"
     });
   }



Friday 18 January 2013

Using find_or_create_by in Rails

Find by one attribute


   User.find_or_create_by_username('beena')

      It will find the record with username 'beena' in table user and if record is not found then it will create a new record with username 'beena'

Find by one attribute or create by multiple attributes


   User.find_or_create_by_username('beenas',
                :first_name => 'beena', 
                :last_name => 'shetty', 
                :role_id => 1)



Find by multiple attributes


   User.find_or_create_by_username_and_role_id('beenas', 2)

      It will find the record with username 'beena' and role_id '2' in table user and if record is not found then it will create a new record with username 'beena' and role_id 2

Find by multiple attributes and pass multiple attribute to a new row to be created


 User.find_or_create_by_username_and_role_id('beenas', 2) do |u|
                u.first_name => 'beena', 
                u.last_name => 'shetty', 
                u.role_id => 1
 end

      It will find the record with username 'beena' and role_id '2' in table user and if record is not found then it will create a new record with username 'beena', role_id 2 and along with other attribute passed.