Register now and start sharing your code snippets.
-->

How to make Rails plugins reloadable

Ruby posted 2 months ago by christian

I found this snippet on the Railshacks blog:

   1  # Array of plugins that you want to be reloaded on each request
   2  reloadable_plugins = ["has_markup"]
   3  
   4  # Remove the plugins from the load_once_paths variable
   5  reloadable_plugins.each do |plugin_name|
   6    reloadable_path = RAILS_ROOT + "/vendor/plugins/#{plugin_name}/lib"
   7    Dependencies.load_once_paths.delete(reloadable_path)
   8  end

Tagged rails, reload, reloadable

How to update the ActiveRecord counter_cache magic column

SQL posted 2 months ago by christian

You can use the model.update_counters method to update the counter_cache column. But if you have a million rows it be very fast.

So for large tables it’s best to do it with a query such as this:

   1  update categories, (select 
   2                        id as category_id, ifnull(count, 0) as count
   3                      from categories left join 
   4                        (select category_id, count(id) as count from products group by category_id) as count_table 
   5                      on 
   6                        categories.id = count_table.category_id) as count_table
   7  set 
   8    categories.products_count = count_table.count
   9  where
  10    categories.id = count_table.category_id

This query updates the count for all rows.

The code needs to be modified for your database design.

Tagged update, counter_cache, sql, rails, active_record

How to profile your Rails and Ruby applications with ruby-prof

Ruby posted 3 months ago by christian

Installing ruby-prof

First install ruby-prof:

   1  git clone git://github.com/jeremy/ruby-prof.git
   2  cd ruby-prof/
   3  rake gem
   4  sudo gem install pkg/ruby-prof-0.6.1.gem

Note that version 0.6.0 doesn’t work, at least not with Rails 2.1.1. With 0.6.0 I got this message:

   1  `gem install ruby-prof` to use the profiler

Setting up a new environment for profiling

Create config/environments/profiling.rb:

   1  config.cache_classes = true
   2  config.action_controller.consider_all_requests_local = false
   3  config.action_controller.perform_caching             = true
   4  config.action_view.cache_template_loading            = true
   5  
   6  #config.log_level = :debug

Add the new environment to database.yml. You might want to reuse the development database.

Creating a profiling script

Next we’ll create a script that simply fetches the homepage, save the following code in profiling/homepage.rb:

   1  get '/'
   2  say "GET / => #{path}"

Run the script

Now run the script 100 times:

   1  RAILS_ENV=profiling ./script/performance/request -n 100 profiling/homepage.rb

Profiling plain Ruby applications

You can also profile a block of code by calling RubyProf from your code:

   1  require 'ruby-prof'
   2  
   3  # Profile the code
   4  RubyProf.start
   5  ...
   6  [code to profile]
   7  ...
   8  results = RubyProf.stop
   9  
  10  File.open "#{RAILS_ROOT}/tmp/profile-graph.html", 'w' do |file|
  11    RubyProf::GraphHtmlPrinter.new(results).print(file)
  12  end
  13  
  14  File.open "#{RAILS_ROOT}/tmp/profile-flat.txt", 'w' do |file|
  15    RubyProf::FlatPrinter.new(results).print(file)
  16  end
  17  
  18  File.open "#{RAILS_ROOT}/tmp/profile-tree.prof", 'w' do |file|
  19    RubyProf::CallTreePrinter.new(results).print(file)
  20  end

Analyzing results

I prefer to use the RubyProf::CallTreePrinter to output data that kcachegrind can read. The HTML and text data is difficult to read so kcachegrind will definitely make your life easier.

On OSX you can install kcachegrind with Fink (or DarwinPorts):

   1  sudo apt-get update ; sudo apt-get install fink
   2  sudo apt-get install kcachegrind

There’s also WinCacheGrind and MacCacheGrind, but I haven’t tried those.

Tagged ruby-prof, rails, gem, profiling, benchmark, profile, kcachegrind

How to backup ActiveRecord model data to YAML with ar_fixtures

Ruby posted 3 months ago by christian

First install the plugin:

   1  script/plugin install http://github.com/mileszs/ar_fixtures/commits/master 

Then dump data for all models with:

   1  rake db:data:dump:all

There’s a task for loading the data into the database, see rake -T for more information.

Tagged fixtures, backup, activerecord, rails, yaml

SEO optimized image URLs with the Paperclip Rails plugin

Ruby posted 3 months ago by christian

Create config/initializers/paperclip.rb:

   1  Paperclip::Attachment.interpolations[:permalink] = lambda do |attachment, style|
   2     attachment.instance.permalink
   3  end

In the model:

   1  has_attached_file :image, 
   2                      :path => ":rails_root/public/images:permalink/:style/:basename.:extension",
   3                      :url => "/images:permalink/:style/:basename.:extension",
   4                      :styles => { :large  => "250x360#",
   5                                   :medium => "150x230#",
   6                                   :small  => "110x150#" }

Instead of URLs like:

/images/products/249/large/temp.jpg

You can get a URL based on, for example, a permalink as in the example above. In my case I get URLs like this:

/images/games/nintendo-wii/large/super-mario-galaxy.jpg

Tagged paperclip, rails, ruby, plugin, seo, url