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

Monday, 30 April 2012

Wrapping pre tag text using css


What Is Pre-Formatted Text?

Pre-formatted text is added to your web pages using the PRE tag.

It is used to be very common to see web pages with blocks of pre-formatted text. Using the PRE tag to define sections of the page as formatted by the typing itself was a quick and easy way to get the text to display as you expected it to. This is because pre-formatted text is defined as text in which the structure is defined by typographic conventions rather than by the HTML.

Try the PRE tag on your website with various different spacings and carriage returns. For example, try pasting the following into your web page HTML (leave the spaces exactly as they are written):


<pre>
    Read each statement
      carefully
         and
      understand
   the meanings....
    Then share them with someone special.
</pre>

Basically HTML collapses the white space in the document. This means that carriage returns, spaces, and tab characters are all collapsed to one space. If you typed the above quote into a typical HTML tag like the P tag, you would end up with one line of text:


    Read each statement carefully and understand the meanings....Then share them with someone special.


The PRE tag leaves the whitespace characters alone. So line breaks, spaces, and tabs are all maintained in the browser. Putting the quote inside a PRE tag results in:


    Read each statement
      carefully
         and
      understand
   the meanings....
    Then share them with someone special.


But the PRE tag does more than just maintain the spaces. In most browseres, it is written in a monospace font. This makes the characters in the text all equal in width. In other words, the letter i takes up as much space as the letter w. But you can change this with style sheets.

Wrapping pre tag text in a div using css


When using pre tags in html to display code blocks it will ignore the div boundaries and not wrap the text by default. By adding some css for pre tags this can be accomplished as follows.

Hint: Another option is to use overflow:auto which will add scroll bars for the content.


pre, code{
 /*Wrap pre tag text for all popular browsers*/
 white-space: pre-wrap; /* css-3 */
 white-space: -moz-pre-wrap !important;  /* Mozilla, since 1999 */
 white-space: -pre-wrap; /* Opera 4-6 */
 white-space: -o-pre-wrap; /* Opera 7 */
 word-wrap: break-word;  /* Internet Explorer 5.5+ */
 /*Or use overflow:auto ----------- */
 /*overflow:auto;*/
}

This will allow your long code to wrap properly and look like this.


Eg:-
ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;ABCDEFGHIJKLMNOPQRSTUVWXYZ;

Friday, 13 April 2012

Creating plugin as mountable engine in rails 3.1 and higher version


What is a Rails Engine?

Engine are miniature Rails applications that you embed into your main application. You can share an Engine across different applications. Since Rails 3.0, every Rails application is nothing more than an Engine, allowing you to share it very easily.

In Rails 3.1 and higher version provides the ability to create a plugin as engine using a single command.

1. Creating engine
      rails plugin new billing --mountable



   It creates a billing folder in the main app.
   I will move this folder into lib folder  or you can keep it there only.

2. Gem file
   This billing module will function as gem in application. In order to function as gem we need  to define this gem in gem file as
      gem 'billing', :path => 'lib/billing'
    Write this code in gem file in path option specify the path while this gem is stored in your application.
   After writing this run bundle install command

3. Mounting engine
    Next important thing is billing/config/routes.rb file:
      Billing::Engine.routes.draw do   
      end
   These are empty routes, but as you can see, they belong to the engine, not to the host application.

   Since engine is now a rack app, you can simply mount it in your application’s routes:
      Rails.application.routes.draw do
        mount Billing::Engine => "/billing"
      end
   This will mount Billing::Engine at /billing path.

4. Isolated Engine
   Normally when you create controllers, helpers and models inside an engine, they are treated as if they were created inside the application itself. This means that all helpers and named routes from the application will be available to your engine’s controllers as well.
However, sometimes you want to isolate your engine from the application, especially if your engine has its own router. To do that, you simply need to call isolate_namespace. This method requires you to pass a module where all your controllers, helpers and models should be nested to:

      module Billing
        class Engine < Rails::Engine
          isolate_namespace Billing
        end
      end
   With such an engine, everything that is inside the MyEngine module will be isolated from the application.

   Write this code inside billing/lib/billing/engine.rb file
   Using isolated engines  the behavior of routes changes. Normally, when you namespace your controllers, you also need to do namespace all your routes. With an isolated engine, the namespace is applied by default, so you can ignore it in routes:

      Billing::Engine.routes.draw do
        resources :invoices
      end
   The routes above will automatically point Biliing::InvoicesController. Furthermore, you don’t need to use longer url helpers like billing_invoices_path. Instead, you should simply use invoices_path as you would do with your application.

5. Migrations
  Engines can have their own migrations. The default path for migrations is exactly the same as in application: db/migrate.

   To create a migration for engine you have go to that path where engine is located
eg:- cd /lib/billing
 Now generate the migration for invoices.
   Notice that migration for that is called create_billing_invoices instead of create_invoices. Also almost all of the files are places in billing/ subdirectory. When you open app/models/billing/invoice.rb, you will see:
      module Billing
        class Invoice < ActiveRecord::Base
        end
      end
   Everything is namespaced for a good reason.We want to avoid conflicts between engine and host application.
   When you run rake db:migrate this migration will not be created. In order to create this migration you have to copy this migration into main app using command
      rake billing:install:migrations
      rake db:migrate

6.  Cross application routes 
   In order to use engines routes in main app

      billing.invoices_path

   In order to use application routes in engine 

      main_app.logout_path




I have created a simple app related to engine. You can check it here https://github.com/BeenaShetty/Engine