Recent notes

RSS feed
December 31, 2011 - (v3.1.0)
0 thanks


I would just use the path_to_image. I find that this is what works best. As it says above it can create problems.

Here is my code

Code example

def background_path(background)
  if background
    path_to_image background.file_name.normal
    path_to_image "background_preview.jpg"

def flavor_path(flavor)
  if flavor
    path_to_image flavor.file_name.normal

basic but gets the job done and it does not have problem with my pre built paths which are called image_path

December 30, 2011
0 thanks

See also: sample

sample randomly picks 1 or n elements from the array

December 29, 2011
0 thanks

Use kill 0 to find out if process is running


#!/usr/bin/env ruby

pid = ARGV[0].to_i

  Process.kill(0, pid)
  puts "#{pid} is running"
rescue Errno::EPERM                     # changed uid
  puts "No permission to query #{pid}!";
rescue Errno::ESRCH
  puts "#{pid} is NOT running.";      # or zombied
  puts "Unable to determine status for #{pid} : #{$!}"

Thanks to http://stackoverflow.com/a/200568/51209

December 17, 2011
2 thanks


[‘one’,‘two’,‘three’].to_sentence # => “one, two, and three”

December 12, 2011
2 thanks

Need to extend class when using this

I had to dig around to find this out - if you want to use memoize somewhere, like an ActiveRecord model, you need to add

extend ActiveSupport::Memoizable

to the class. This doesn’t seem to be explained anywhere (the only docs are 3 year old blog posts anyway).

December 8, 2011
1 thank

hidden field can be changed by JS

Plumba, it’s not that useless if you think about possibility to change a hidden field with JS

December 5, 2011
0 thanks

Not available

Actually, this method is not available now.(github.com/ruby/ruby/blob/trunk/rational.c#L2352)

December 2, 2011 - (>= v3.0.0)
0 thanks

Difference in DateTimes ...

Mostly, the database date columns are DateTime instances. Whereas Rails adds several useful utility functions to DateTime (in activesupport), there is some confusing behavior. This is at least somewhat surprising.

Two subtract two DateTime instances, you should always “round” the returned value. Suppose:

d1 = DateTime.now d2 = d1 - 5.days.ago

then, d1 - d2 is a Rational, which tells you the difference between dates only after rounding. Thus, diff_in_days = (d1 - d2).round

December 1, 2011 - (>= v3.0.0)
1 thank

This method isn't deprecated

This method was moved to AbstractController::Callbacks, as stated on [1].

It took me a while to figure out ‘what should I use instead before_filter’. Hope this helps anyone that hits the same road I’m in.

November 29, 2011
0 thanks

index doesn't work

@ssoroka even I’m having same issue. how did you resolve it?

November 21, 2011
0 thanks

Custom configuration keys

It is nice to know, that you can store any custom configuration key in configure block… E.g.

YourApp::Application.configure do
   # ...
   config.my_custom_setting = "QWERTY1234"

Then you can just access it by calling

November 21, 2011 - (>= v3.1.0)
0 thanks

Rails 3.1 - Use request.url instead

As request.request_uri has been deprecated, use



November 16, 2011
1 thank

Change in clone for ActiveRecord objects in ruby-1.9.3

I noticed that cloning an active record object in ruby-1.9.3 and then changing an attribute on the original object will actually change the cloned object as well. This was not the case in ruby-1.9.2.

November 16, 2011
1 thank

Alternative definition

a.flat_map(&b) works exactly like a.map(&b).flatten!(1).

November 16, 2011
0 thanks

Examples in a readable format :)

Here are the above examples in a somewhat more readable format:

# Assert a basic route: a controller with the default action (index) 
assert_routing/home’, :controller =>home’, :action =>index’
# Test a route generated with a specific controller, action, and parameter (id) 
assert_routing/entries/show/23’, :controller =>entries’, :action =>show’, :id => 23
# Assert a basic route (controller + default action), with an error message if it fails 
               { :controller =>store’, :action =>index’ }, 
               {},Route for store index not generated properly’
# Tests a route, providing a defaults hash 
               {:id =>9”, :item =>square”}, 
               {:controller =>controller”, :action =>action”}, 
               {:item =>square”}
# Tests a route with a HTTP method 
assert_routing({ :method =>put’, :path =>/product/321’ }, 
               { :controller =>product”, :action =>update”, :id =>321” })
November 15, 2011 - (v3.1.0)
0 thanks

Wrapping with select tag

I didn’t knew how to wrap the output with <select> tag. I didn’t want to use raw html, but the doc doesn’t mention another way.

So, here is what I tried and it’s working:

<%= f.select :entry, option_groups_from_collection_for_select(@categories, :entries, :name, :id, :name) %>

I hope this helps anyone. :-)

November 14, 2011 - (v3.1.0)
2 thanks


For Rails 3.1 check see:

http_basic_authenticate_with :name => "username", :password => "pass" 
November 12, 2011 - (v2.0.0 - v2.3.8)
0 thanks

Specify attachment names

If you want to give your attachment a name, you can do this:

attachment :filename => 'my_file.txt', :body => File.read('/var/null')

It will appear to the recipient as a file named “my_file.txt” rather than something awful like “noname 1”.

November 11, 2011
3 thanks

Catching and throwing -- don't!

@wiseleyb and @glosakti, neither of your suggestions are necessary, and both are bad practices.

This test:

test "transactions" do
  assert_raises ZeroDivisionError do
    User.transaction do

passes just fine on its own, with the transaction rolled back as you’d expect. No need to hack something ugly together.

November 10, 2011
0 thanks

logic in class/id

If you need to place some simple logic in class or like that, I think that best to make it with simple brackets:

Code example

<%= link_to ‘All actions’, switch_action_tab_path, :remote => true, :class => (‘selected’ if @tab == ‘all’) %>

November 7, 2011 - (v3.0.5 - v3.0.9)
1 thank

unscoped.all / unscoped.count

At least in console, doing unscoped.all or unscoped.count initially returns expected results but, after you’ve added new records outside of the default_scope those two calls seem to use some cached values.

Therefore it should always be used with the block (as they sort of imply in the doc). unscoped { all } and unscoped {count }

November 6, 2011 - (>= v3.1.0)
3 thanks

Removed in 3.1.x

This method (and #auto_link_urls) has been removed in Rails 3.1 - other options are out there, such as Rinku, however there is a gem you can use for migration purposes etc, which is rails_autolink: http://rubygems.org/gems/rails_autolink

October 26, 2011
2 thanks

Adding to the URL

If you want to use polymorphic routing for your object but you also need to specify other stuff like an anchor, you can explicitly generate the polymorphic url with extra options:

form_for @candidate,
  :url => polymorphic_path(@candidate, :anchor => 'signup')
October 19, 2011 - (>= v3.0.0)
3 thanks

Replaced by :on => :create

From rails 3,


has been removed and replaced with:

before_validation :foo, :on => :create
October 18, 2011
0 thanks

Upgrading to 3.x


Since this is deprecated, one can watch the Railcast for upgrading to 3.x

The equivalent is the ActiveRecord finder methods. http://apidock.com/rails/ActiveRecord/Fixture/find

October 10, 2011 - (>= v3.1.0)
1 thank

Use Ruby instead!


class TestClass < SomeSuperClass
  attr_accessor :sample_acc

  def initialize      
    @sample_acc = []

If nil is not a valid value for this accessor, then you can just define reader for it.

class TestClass
  attr_accessor :sample_acc

  def sample_acc
    @sample_acc ||= 98