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.

Friday 30 November 2012

Use Cpanel and WHM API's In Rails


  WHM 
       WebHost Manager (WHM) is a web-based tool used by server administrators and resellers to manage hosting accounts on a web server.
       WHM listens on ports 2086 and 2087 by default.

   cPanel
      cPanel is a Unix based web hosting control panel that provides a graphical interface and automation tools designed to simplify the process of hosting a web site. cPanel utilizes a 3 tier structure that provides functionality for administrators, resellers, and end-user website owners to control the various aspects of website and server administration through a standard web browser.
     cPanel is commonly accessed on port 2082, with an SSL-secured server operating on port 2083.

  Use cpanel and Whm API's in Rails
        Panelbeater gem  is used for communicating with the cPanel and WHM API's.
        Ruby library for the WHM & cPanel API.
   
  Installation
       Github path https://github.com/BeenaShetty/panelbeater
       Specify gem 'panelbeater' in gemfile

 Usage
   Create a server object and connect to WHM using host and secure hash:

      server = Panelbeater::Whm::Commands.new(
                           :url => url,
                           :api_key => secure_hash,
                           :port => port,
                           :user => username
                        )

   Now,you can access the modules of WHM by calling server.module


Example
    Creating a new account
        Requires only a username and domain

        result = server.createacct(
                  :username => 'newuser',
                  :domain   => 'newuser.com'
                )

Output

  createaact  =>  {result  => { :status  =>  boolean,  :statusmsg  =>  "" }}

  status (boolean) — Status of the operation.
      1 — success.
      0 — failure.

  statusmsg (string) — Status or error message.

  Reference CreateAccount

    Delete account
        Requires only username

      result = server.removeacct(:user => 'newuser')

Output

  removeacct  => {result  => { :status  =>  boolean,  :statusmsg  =>  "" }}

  status (boolean) — Status of the operation.
      1 — success.
      0 — failure.

statusmsg (string) — Message about the status of the operation.

ReferenceRemoveAccount


  Using Cpanel methods
    Connect to cpanel using server.cpanel
     domain = Domain.find(5)
     server.cpanel(domain.username, {
                   :cpanel_jsonapi_module => api_module,
                   :cpanel_jsonapi_func => api_function,
                   :cpanel_jsonapi_apiversion => api_version
       })


Note: If you use a cPanel port (2082 or 2083) to access the XML or JSON API, you can only use it to run API1 and API2 functions. Native XML and JSON API calls will not work. The ports are assigned as follows:

    2082 — cPanel (unsecured).
    2083 — cPanel (secured).
    2086 — WHM (unsecured).
    2087 — WHM (secured).



Fast Mode

  Fast Mode is a newer way to use the cpanel function call in the XML or JSON API. This method is preferred, since it simplifies building the request, no longer requiring you to enter XML tags as input. The server-side processing of Fast Mode requests is also much quicker than the processing of XML requests.

XML Input

  The cpanel XML function call in Fast Mode takes the following variables as input.

  The following variables are required:

      cpanel_xmlapi_user (string) — The user as whom you wish to call the function.
      cpanel_xmlapi_module (string) — Name of the module to access.
      Important: API1 and API2 variables are case-sensitive. For example, specifying Email is different from specifying email.
      cpanel_xmlapi_func (string) — Name of the function to access.

  The following variables are optional, depending on the call:

      cpanel_xmlapi_apiversion (integer) — Version of the API to access.
          1 — API1.
          2 — API2.
          No input — Defaults to API2.
      arg (string) — List of arguments. These variables are numbered such that the first is arg-0, the second is arg-1, and so on.
        Example: arg-0=username&arg-1=somepass

JSON Input
    The cpanel JSON function call in Fast Mode takes the following variables as input.

  The following variables are required:

      cpanel_jsonapi_user (string) — The user as whom you wish to call the function.
      cpanel_jsonapi_module (string) — Name of the module to access.
    Important: API1 and API2 variables are case-sensitive. For example, specifying Email is different from specifying email.
      cpanel_jsonapi_func (string) — Name of the function to access.

  The following variables are optional, depending on the call:

      cpanel_jsonapi_apiversion (integer) — Version of the API to access.
          1 — API1.
          2 — API2.
          No input — Defaults to API2.
    API1: arg (string) — List of arguments. These variables are numbered such that the first is arg-0, the second is arg-1, and so on.
          Example: arg-0=username&arg-1=somepass
      API2: arg (string) — List of arguments. These variables are given by name.
          Example: email=bob&domain=fred.com

Output

    cpanelresult — Container for the result of the cPanel operation.
        apiversion (string) — Version of API accessed (1 or 2).
        module (string) — Name of the module accessed.
        func (string) — Name of the function accessed.
        type (string) — Type of function.
        source (string) — Source of the call (internal or external).
        data — Data provided by the function.
         result (string) — Result of the function

Reference: Cpanel

Example
1. Email::listpopswithdisk
      List email accounts associated with a particular domain.

     server.cpanel(domain.username, {
                   :cpanel_jsonapi_module => "Email",
                   :cpanel_jsonapi_func => "listpopswithdisk",
                   :cpanel_jsonapi_apiversion => 2
       })


2. Email::addpop
     Add(create) an e-mail account.
 
     server.cpanel(domain.username, {
                   :cpanel_jsonapi_module => "Email",
                   :cpanel_jsonapi_func => "addpop",
                   :cpanel_jsonapi_apiversion => ,
                   :domain => "user.com",
                   :email => "test",
                   :password => "12345",
                   :quota => 10
       })


Output

   <data>
     <reason> A string value that contains the email address if the function completes successfully. This value will contain a reason for failure if the function encounters an error.
    </reason>
    <result> A boolean value that indicates success or failure. '1' indicates that the function completed successfully.
    </result>
   </data>


Reference: API1 Version , API2 Version



Thursday 18 October 2012

Calender in Javascript



Recently i was searching for a calender to implement in my Rails app. I came across a jquery plugin named jquery.ui.datetimepicker . I forked that repository from github and implemented it. Added time functionality in it and also made changes according to my requirement.
 But their was no document related to it. So i thought to write blog about it and also i have created a demo app.

  Download
    Download  all the js file, css file and images related to it from        "https://github.com/BeenaShetty/jquery.ui.datetimepicker" this link.

  Requirement
    Include this files in your application.

  Usage
      jQuery(document).ready(function(){
         jQuery(input-target-selector).datetimepicker();
      });

where the input-target-selector naturally is  class or id of a selector (eg.  .datepickers or #picker). The datetimepicker will be effective for all selected input element .

 

DEMO APP

Wednesday 3 October 2012

Rails Console Tips



1.To call Applicationcontroller methods from the Console



    ApplicationController.new.methods
    => :hello, :current_user, :create_support_user

          It will display all the methods of application controller


    ApplicationController.new.hello
    => "Hello World"

          Here :hello is the method defined inside application_controller.

     Note: Instead of using ApplicationController.new you can also use controller.methods 
     Check this link for more details related to controller 

2. To use Helper methods from the Console


 
    ApplicationController.helpers.methods
    => :admin?, :client?   
     OR
    helper.methods
    => :admin?, :client?    

         It will display all the helper methods
   
    helper.number_to_currency(100)
    => "$100.00"
    helper.truncate("Testing User", length: 2)
    => "Testing Use..."
    helper.pluralize(2, "Person")
    => "2 People" 


3. Who defined helper?

    
    helper.method(:truncate)
    => #<Method: ActionView::Base(ActionView::Helpers::TextHelper)#truncate> 
    helper.method(:link_to)
    => #<Method: ActionView::Base(ActionView::Helpers::UrlHelper)#link_to> 
    helper.method(:number_to_currency)
    => #<Method: ActionView::Base(ActionView::Helpers::NumberHelper)#number_to_currency 


4. app

    
    app.class
    => ActionDispatch::Integration::Session

  i. Routes
  
    app.overview_admin_index_path()
    => "/admin/overview"   
    app.edit_user_registration_path(User.first)
    =>/users/edit.12" 

  ii. Url

    app.url_for(:controller => :admin)
    => "http://www.example.com/admin" 
    app.url_for(:controller => :admin, :action => :overview)
    => "http://www.example.com/admin/overview"

  iii. Submit request 
    To make request from console

   app.get "/users/sign_in"
   => 200

   app.session
   => {"session_id"=>"786731e9880c620cf638b57a4db88a1e", "user_return_to"=>"/admin/overview", "flash"=>#, @closed=false, @flashes={:alert=>"You need to sign in or sign up before continuing."}, @now=nil>, "_csrf_token"=>"kvMbabanAsi07gEfsuzHdR7xnCEz0hMIvRBU2LiaqFs="} 
 
   app.get "/users/sign_in",{:username => 'new_user', :password => '123456789'}
   => 200

   app.cookies
   => #<Rack::Test::CookieJar:0xbf005a4 @default_host="www.example.com", @cookies=[#<Rack::Test::Cookie:0xba68e24 @default_host="www.example.com", @name_value_raw="_snipper_host_india_session=BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTc4NjczMWU5ODgwYzYyMGNmNjM4YjU3YTRkYjg4YTFlBjsAVEkiE3VzZXJfcmV0dXJuX3RvBjsARkkiFC9hZG1pbi9vdmVydmlldwY7AEZJIhBfY3NyZl90b2tlbgY7AEZJIjFrdk1iYWJhbkFzaTA3Z0Vmc3V6SGRSN3huQ0V6MGhNSXZSQlUyTGlhcUZzPQY7AEY%3D--152f06b94ca610d662cfd7148b7a4a49ceac23eb", @name="_snipper_host_india_session", @value="BAh7CEkiD3Nlc3Npb25faWQGOgZFRkkiJTc4NjczMWU5ODgwYzYyMGNmNjM4YjU3YTRkYjg4YTFlBjsAVEkiE3VzZXJfcmV0dXJuX3RvBjsARkkiFC9hZG1pbi9vdmVydmlldwY7AEZJIhBfY3NyZl90b2tlbgY7AEZJIjFrdk1iYWJhbkFzaTA3Z0Vmc3V6SGRSN3huQ0V6MGhNSXZSQlUyTGlhcUZzPQY7AEY=--152f06b94ca610d662cfd7148b7a4a49ceac23eb", @options={"path"=>"/", "HttpOnly"=>nil, "domain"=>"www.example.com"}>]>


  iv. Response

   app.response
     It will display full html code

   app.response.response_code
   => 200

   app.response.body[0..100]
   => "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml"

   app.path
   => "/users/sign_in"


4. Method location

      To get exact source loaction of particular method using Method#source_location

    User.instance_method(:role?).source_location
    =>["/home/Desktop/Workspace/host_india/app/models/user.rb", 32] 

     Let's try for app

    app.method(:post).source_location
    => ["/home/gvo/.rvm/gems/ruby-1.9.2-p318/gems/actionpack-3.2.6/lib/action_dispatch/testing/integration.rb", 38] 


5. Accessing the last return value


   "Hello"
   => "Hello" 
   str = _
   => "Hello" 
   str
   => "Hello" 

   Commission.first
   => #
   _.amount
   => 4947.3

Thursday 9 August 2012

Difference between find() and filter() in jquery

find()  

     searches through all the child elements in the matched set.  

  Description:
          Get the descendants of each element in the current set of matched elements,  filtered by a selector.

  Syntax  
      .find( selector )
             selector: A string containing a selector expression to match elements against.

     .find( jQuery object )
           jQuery object: A jQuery object to match elements against.

     .find( element )
           element: An element to match elements against.

 filter()

      searches through all elements in the matched set.  

  Description:
        Reduce the set of matched elements to those that match the selector or pass the function's test.  

  Syntax 
     .filter( selector )
            selector: A string containing a selector expression to match the current set of elements against.

    .filter( function(index) )
           function(index): A function used as a test for each element in the set. this is the current DOM element.

    .filter( element )
          element: An element to match the current set of elements against.

    .filter( jQuery object )
         jQuery object:  An existing jQuery object to match the current set of elements against.


Example 

    
   <html>
     <head>
       <script src="jquery_1.7.1.min.js" type="text/javascript"></script>
       <script type="text/javascript">
          function filter_month(obj){
              jQuery('div').css('background','white');
               jQuery('div').filter(obj).css('background', '#83AFF8');
             }

         function find_month(obj){
             jQuery('div').css('background','white');
             jQuery('div').find(obj).css('background', '#83AFF8');
          }
       </script>
    </head>
    <body>   
       <div id="months">
          <table>
            <tr>
               <td> January </td>
               <td> February </td>
               <td> March </td>
               <td> April </td>
            </tr>
            <tr>
               <td> May </td>
               <td> June </td>
               <td> July </td>
               <td> August </td>
             </tr>
             <tr>
               <td> September </td>
               <td> October </td>
               <td> November </td>
               <td> December </td>
            </tr>
            </table>
       </div>
       <div> 
        <b> Category</b>
         <div id="months"> Month </div>
         <div id="weeks"> Weeks </div>
       </div>
       <input onclick = "filter_month('#months');" type = "button" value ="Filter" />
       <input onclick = "find_month('#months');" type = "button" value ="Find" />
   </body>
  </html>





January February March April
May June July August
September October November December


Category
Month
Weeks


Friday 18 May 2012

Get models and controllers list inside rails application


Get collection of models inside your application.


 1. Get table names inside database 

  ActiveRecord::Base.connection.tables.map do |model|
    model.capitalize.singularize.camelize
  end

  =>["Blog", "User", "UserDetail"]


 2. Load models dir

  @models = Dir['app/models/*.rb'].map {|f| File.basename(f, '.*').camelize.constantize.name }


 3. ActiveRecord subclasses
     It will only get base class models not inherited models.

# make sure that  relevant models are loaded otherwise
# require them prior
# Dir.glob('#{RAILS_ROOT}/app/models/*.rb').each { |file| require file }
   class A < ActiveRecord::Base
   end

   class B < A
   end

   class C < B
   end

  ActiveRecord::Base.subclasses.each{|x| x.name }

  =>["A"] 


 4. Inherited model
     It will get both base class models and inherited models using descendants.

# make sure that  relevant models are loaded otherwise
# require them prior
# Dir.glob('#{RAILS_ROOT}/app/models/*.rb').each { |file| require file }
   class A < ActiveRecord::Base
   end

   class B < A
   end

   class C < B
   end

  ActiveRecord::Base.descendants.each{|x| x.name }

  =>["A", "B", "C"]


Get collection of controllers inside your application.


 1. ApplicationController subclasses
     It will get all controller classes.

  ApplicationController.subclasses

  =>["AccountsController", "BlogsController", "UsersController"]


 2. Inherited Controller
      It is get all controller classes along with inherited controller classes.

  class AccountsController < ApplicationController
  end

  class ArticlesController < ::AccountsController
  end

  ApplicationController.descendants

  =>["AccountsController", "BlogsController", "UsersController", "AccountsController", "ArticlesController"]


Note:
   require all files in "#{RAILS_ROOT}/app/controllers" to populate your list in development mode.
   It'll get you started, but keep in mind that in development mode you won't see much, because it will only show you what's actually been loaded. Fire it up in production mode, and you should see a list of all of your controllers.



To get all the actions in a controller, use action_methods



  PostsController.action_methods