Recent notes
RSS feed colinsurprenant -  
    October  3, 2011 - (>= v1_9_1_378)
 colinsurprenant -  
    October  3, 2011 - (>= v1_9_1_378)
    
  example will not work in 1.9+
Since 1.9 introduces native threads, we cannot assume the order of exectution and the example above is not thread safe and fails with a “deadlock detected (fatal)” error. Also Thread.pass is pointless in the context of native threads.
This will work as intended with native threads:
a = Thread.new { print "a"; Thread.stop; print "c" } sleep(0.1) until a.status == 'sleep' print "b" a.run a.join
 weexpectedTHIS -  
    October  3, 2011
 weexpectedTHIS -  
    October  3, 2011 
    
  @Mange
If you’re actually looking to cut down on code why not use .map instead of the longer .collect?
 hardbap -  
    September 30, 2011 - (>= v3.0.0)
 hardbap -  
    September 30, 2011 - (>= v3.0.0)
    
  Using a block with image_tag
HTML5 officially supports block-level elements in the anchor tag and Rails 3 allows you to pass a block to image_tag:
<%= image_tag(some_path) do %>
<%= content_tag(:p, "Your link text here")
<% end %>
 leente -  
    September 30, 2011 - (v3.0.0 - v3.1.0)
 leente -  
    September 30, 2011 - (v3.0.0 - v3.1.0)
    
  Without module
If you want to have only the path prefix without namespacing your controller, pass :module => false.
Normal:
namespace :account do resources :transactions, :only => [:index] end account_transactions GET /account/transactions(.:format) {:controller=>"account/transactions", :action=>"index"}
With :module => false:
namespace :account, :module => false do resources :transactions, :only => [:index] end account_transactions GET /account/transactions(.:format) {:controller=>"transactions", :action=>"index"}
 redconfetti -  
    September 29, 2011 - (<= v3.1.0)
 redconfetti -  
    September 29, 2011 - (<= v3.1.0)
    
  Additional Format meaning
%e - Day of the month, without leading zero (1..31)
 jrochkind -  
    September 27, 2011 - (>= v3.1.0)
 jrochkind -  
    September 27, 2011 - (>= v3.1.0)
    
  1.9 behavior
“In Ruby 1.9 and newer mb_chars returns self’”
This would seem to be a lie. At least in rails 3.1.0 and ruby 1.9.2, mb_chars still returns a proxy object with additional useful methods defined on it that aren’t on a 1.9.2 String.
ruby-1.9.2-p180 :007 > "àáâãäå".normalize(:kd) NoMethodError: undefined method `normalize' for "àáâãäå":String ruby-1.9.2-p180 :008 > "àáâãäå".mb_chars.normalize(:kd) => àáâãäå
 joshuapinter -  
    September 25, 2011
 joshuapinter -  
    September 25, 2011 
    
  Parsing the Date Params into a New Date Object.
Useful for when you need to create a Date object from these manually, such as for reporting.
If the date select input is start_date and it belongs to the report form object:
@start_date = Date.civil(params[:report]["start_date(1i)"].to_i, params[:report]["start_date(2i)"].to_i, params[:report]["start_date(3i)"].to_i) @start_date.class # => Date @start_date # => Sun, 25 Sep 2011 # For example.
Use a similar method for DateTime situations.
 abstraktor -  
    September 17, 2011
 abstraktor -  
    September 17, 2011 
    
  this works, but doesn't make sense
does it?
replace(klass.find(ids).index_by { |r| r.id }.values_at(*ids))
equals
replace(klass.find(ids))
I see no point in making it that complicated
 jrochkind -  
    September 15, 2011
 jrochkind -  
    September 15, 2011 
    
  beware of trying to dup in subclass inside class context
The example of adding to an array without effecting superclass:
# Use setters to not propagate changes: Base.setting = [] Subclass.setting += [:foo]
That’s right as far as it goes. But beware when you are in context of class definition:
class Subclass < Base # possibly wrong, ruby seems to get # confused and think you mean a local # var, not the class ivar setting += [:foo] # But this will work: self.setting += [:foo] # Or: self.setting = self.setting.dup self.setting << :foo [...] end
 joshuapinter -  
    September 14, 2011
 joshuapinter -  
    September 14, 2011 
    
  Find a Selected Option in a Drop Down.
You can find the selected option (or options for multiple select inputs) with the following:
assert_select('select#membership_year option[selected]').first['value']
 MGPalmer -  
    September 14, 2011
 MGPalmer -  
    September 14, 2011 
    
   ssoroka -  
    September 13, 2011
 ssoroka -  
    September 13, 2011 
    
  more options
useful options are:
:root => ‘object’, :skip_instruct => true, :indent => 2
:builder can also be used to pass your own Builder::XmlMarkup instance.
 stevo -  
    September 13, 2011
 stevo -  
    September 13, 2011 
    
  Some unexpected behaviour
When using Array as default value, it behaves more like cattr_accessor…
class A attr_accessor_with_default :b, [] end x = A.new x.b << 1 #puts x.b.inspect => [1] y = A.new y.b << 2 #puts y.b.inspect => [1, 2]
 bsodmike -  
    September  9, 2011 - (v3.0.9)
 bsodmike -  
    September  9, 2011 - (v3.0.9)
    
   MMSequeira -  
    September  8, 2011 - (>= v3.0.9)
 MMSequeira -  
    September  8, 2011 - (>= v3.0.9)
    
  First example simplified
The first code example may be simplified, since the call to method to_xml is made implicitly anyway:
def index @people = Person.find :all respond_to do |format| format.html format.xml { render :xml => @people } end end
 digger69 -  
    September  7, 2011 - (v3.0.0 - v3.0.9)
 digger69 -  
    September  7, 2011 - (v3.0.0 - v3.0.9)
    
  Tested w/ Rails 3 and returning true/false ignored
Per http://ar.rubyonrails.org/classes/ActiveRecord/Callbacks.html “If a before_* callback returns false, all the later callbacks and the associated action are cancelled. If an after_* callback returns false, all the later callbacks are cancelled.” [and presumably associated action is not canceled]
So, the callback chain will be broken, but the save will still happen.
Also ran into this: http://innergytech.wordpress.com/2010/03/08/dont-put-validations-in-after_save/
 MMSequeira -  
    September  7, 2011 - (>= v3.0.9)
 MMSequeira -  
    September  7, 2011 - (>= v3.0.9)
    
  Passing an object as argument
It is possible to pass an instance of a record to the method. See the documentation of polymorphic_url (http://apidock.com/rails/ActionDispatch/Routing/PolymorphicRoutes).
 joshuapinter -  
    September  5, 2011
 joshuapinter -  
    September  5, 2011 
    
  (Another) Pluralize Without Showing the Count
Thought it would be best to take the source code from pluralize and just remove the count from the output.
Create this helper method in application_helper.rb
# Pluralize without showing the count. def simple_pluralize count, singular, plural=nil ((count == 1 || count =~ /^1(\.0+)?$/) ? singular : (plural || singular.pluralize)) end
This allows you to pass in in the plural word to use as well.
 amasses -  
    August 30, 2011 - (>= v3.0.0)
 amasses -  
    August 30, 2011 - (>= v3.0.0)
    
  Does not work for has_one associations
If you are using this to validate that a has_one association has been made with another object this will not work, as the test used in the AssociatedValidator #validates_each method tests for nil and then ignores this object.
To test for association with a has_one association you can use the following code:
validate do [:teacher, :book].each do |attr| errors.add(attr, "is required") if self.send(attr).nil? end end
 george -  
    August 24, 2011 - (>= v3.0.9)
 george -  
    August 24, 2011 - (>= v3.0.9)
    
   allenb -  
    August 23, 2011
 allenb -  
    August 23, 2011 
    
  the correct return value of html_escape in example above
the correct return is:
# => is a > 0 & a < 10?
 syborg -  
    August 19, 2011
 syborg -  
    August 19, 2011 
    
  Alternative way to show relative paths from absolute globbing
An alternative to show relative paths is using the well known String#sub! method
base_dir = File.expand_path("my_dir") << "/" # don't miss adding "/" files = Dir[File.join(base_dir, '**', '*.html.gz')] p files.map {|f| f.sub!(base_dir,"")}
 gabeodess -  
    August 15, 2011
 gabeodess -  
    August 15, 2011 
    
  The :path option
The path option will actually set the path and not the prefix I have found in Rails 3.0.5.
Example
resources :my_reports, :path => 'my-reports'
All actions for this resource will now be at /my-reports.
 aamer -  
    August 14, 2011
 aamer -  
    August 14, 2011 
    
  Security issue
One thing to note about the code above is that it could have a security issue. If the user changes his/her password, the authentication token should expire. Hence, in a production scenario you should put in the password salt or something to allow the token to become invalidated.
 anexiole -  
    August 14, 2011
 anexiole -  
    August 14, 2011 
    
  stub/stub! will always be followed by '.and_return'
this function will aways be followed by ‘.and_return(…)’ because a stub is typically used for returning values. The required argument given to stub is a method name. When a message to this stubbed method name is received by a class or existing object of the class AND ‘.and_return’ is provided, the stub will return whatever was provided as argument to ‘.and_return’.
For example,
HomeLoan.stub!(interest_rate).and_return(‘5.5%’)
- 
this will return 5.5% when a message for interest_rate in a HomeLoan class’s object is received. 
HomeLoan.stub!(interest_rate).and_return(‘5.5%’, ‘3%’)
- 
this will return 5.5% when a message for interest_rate in a HomeLoan class’s object is received FOR THE FIRST TIME but will return 3% for subsequent calls/messages. 
 artemave -  
    August 11, 2011
 artemave -  
    August 11, 2011 
    
   Vidmantas -  
    August 11, 2011 - (>= v3.0.0)
 Vidmantas -  
    August 11, 2011 - (>= v3.0.0)
    
  Look at mail gem
If you’re looking for mailer methods like “deliver” for rails 3 or later, you should look into “mail” gem: http://github.com/mikel/mail
 amasses -  
    August  9, 2011
 amasses -  
    August  9, 2011 
    
  HTML5 support
To support multiple file selection simply pass :multiple => true in the options hash:
file_field_tag 'file', :accept => 'image/jpeg', :multiple => true
 THAiSi -  
    August  5, 2011
 THAiSi -  
    August  5, 2011 
    
  Speccing read_only requirements
To test if an attribute is defined readonly:
class MyModel < ActiveRecord::Base attr_readonly :important_type_thingie end #RSpec describe MyModel do its('class.readonly_attributes') { should include "important_type_thingie" } it "should not update the thingie" do m = create :my_model, :important_type_thingie => 'foo' m.update_attributes :important_type_thingie => 'bar' m.reload.important_type_thingie.should eql 'foo' end end
 victorgrey -  
    August  4, 2011
 victorgrey -  
    August  4, 2011 
    
  Examples out of order
The second and third examples should exchange places to fit with their explanations.

 RSpec
RSpec Ruby on Rails
Ruby on Rails Ruby
Ruby 
    