Showing posts with label rails 3. Show all posts
Showing posts with label rails 3. Show all posts

Saturday, May 28, 2011

Convert string to a class/model

This post is related to how to convert string to class ( model ). I came across this situation while migrating one of my organization's project on rails 3.

Many times we came across a situation where we need to convert a string to respective class or model. So that we can call methods on it. Generally to handle this situation new rails developers use case statement like this,

case class_name_string
when 'Account'
object = Account.find(id)

when 'Contact'
object = Contact.find(id)

when 'Opportunity'
object = Opportunity.find(id)

when 'Campaign'
object = Campaign.find(id)

when 'Model1'
object = Model1.find(id)

when 'Model2'
object = Model2.find(id)
:
:
:
:
when 'Modeln'
object = Modeln.find(id]) 
end

This can be actually done pretty easily by using constantize in only one line

class_name_string.constantize.find(id)

Friday, April 15, 2011

Configure Rack-bug for rails 3

While migrating one of my rails application on rails 3, I thought of using rack-bug simultaneously for improving performance.

Following are the steps which I used for configuring rack-bug for rails 3 (3.0.6).


1. Install rack-bug (branch rails3) as plugin
   cd vendor/plugins
   git clone -b rails3 https://github.com/brynary/rack-bug.git


If you want to you it as gem then add following line into Gemfile
gem 'rack-bug', :git => 'https://github.com/brynary/rack-bug.git', :branch => 'rails3'


2. Replace the code from file actionview_extension.rb
which is avilable in vendor/plugins/rack-bug/lib/rack/bug/panels/templates_panel/ as specified in bug of rack_bug repository


if defined?(ActionView) && defined?(ActionView::Template)
  ActionView::Template.class_eval do
    def render_with_rack_bug(*args, &block)
      Rack::Bug::TemplatesPanel.record(virtual_path) do
        render_without_rack_bug(*args, &block)
      end
    end
    alias_method_chain :render, :rack_bug
  end
end

If you are using gem override the specified file in some way


3. Add following lines into your config.ru
   require 'rack/bug'
   use Rack::Bug, :secret_key => "someverylongandveryhardtoguesspreferablyrandomstring"
   run myapp


4. Start your server and access the URL http://your_app/__rack_bug__/bookmarklet.html
   and enter the password.