Recent good notes
RSS feedUsing block version in Ruby < 1.8.7
The block usage was added in 1.8.7, so to get the same functionality in an earlier version of Ruby, you need to utilize the find method.
Here is a quick example:
match = list.find { |l| l.owner == myself } match_index = list.index(match)
If you do some gymnastics, you can have it on one line without extra variables:
match_index = list.index(list.find { |l| l.owner == myself })
Options
Available options are (none of these exists by default):
* :limit - Requests a maximum column length. This is number of characters for :string and :text columns and number of bytes for :binary and :integer columns. * :default - The column‘s default value. Use nil for NULL. * :null - Allows or disallows NULL values in the column. This option could have been named :null_allowed. * :precision - Specifies the precision for a :decimal column. * :scale - Specifies the scale for a :decimal column.
Be careful with name of attribute writer
If restricting access to attributes you normally get code like
attr_accessible :foo,
When using these nested attributes you end up with code like
attr_accessible :foo, :bar_attributes
Its very easy to leave of the _attributes suffix e.g
attr_accessible :foo, :bar
which will cause you all sorts of problems
Optional local assigns
When you have a partial with optional local assigns, for instance:
<%= render :partial => 'articles/preview' %> <%= render :partial => 'articles/preview', :locals => { :show_call_out => true } %>
And you don’t want the partial to break when the local isn’t assigned, you can reference it through the local_assigns local variable instead of through the template binding:
<% if local_assigns[:show_call_out] %> <em><%= format @article.call_out %></em> <% end %>
Not really deprecated
This isn’t really deprecated, it’s just relocated to ActiveRecord::AttributeMethods#read_attribute
Important note
It has been said that “it can be compared to, but isn’t the same thing as”:
class Bar class << self attr_accessor :greeting end end
Which is true. However, they are “inherited” isn’t exactly the case. Rather, cattr_accessor uses class variables.
The problem with class variables in Ruby, is that a class variable is the same object across all subclasses of a class. Consider the following example of what happens with cattr_accessor:
class A @@foo = 'foo' def self.foo @@foo end end p A.foo # => "foo" class B < A end p B.foo # => "foo" class B @@foo = 'bar' end p B.foo # => "bar"
So far so good you might think. However, something you might not have expected is that the variable has now also changed in class A:
p A.foo # => "bar"
This is in my opinion almost never what you’d want. More probable is that you’d want the individual class instance to have an accessor. (Remember classes are objects in Ruby). I do the following in regular Ruby:
class A class << self attr_accessor :foo end self.foo = 'foo' end p A.foo # => "foo" class B < A end p B.foo # => nil class B self.foo = 'bar' end p B.foo # => "bar" p A.foo # => "foo"
As you can see, this returns nil when a value hasn’t explicitly been set yet on the new class instance. If you’d like to have inheritance without messing with the superclasses variables, have a look at ActiveSupport’s class_inheritable_accessor, which does the same as I just explained, but creates a clone of the object and assigns it to the subclass whenever a class is inherited.
What I’d normally do in Ruby to fix the issue of it returning nil is to create the accessor manually and have it set the instance variable to the default if it’s nil:
class A class << self def foo @foo ||= 'foo' end end end class B < A end p B.foo # => nil
So to recap:
-
cattr_accessor uses class variables (@@foo), in which case the object is shared across all subclasses of a class. Use it mainly for static data, in which case you’d probably best use a constant.
-
class_inheritable_accessor (or what I showed) uses instance variables (@foo) at the Class instance level. These variables are not shared across all subclasses.
Expensive method!
This method builds the a new hash every time it’s called, so be cautious not to use it in loops etc.
Skipping validation
Unlike the save method, you can’t pass false to update_attributes to tell it to skip validation. Should you wish to do this (consider carefully if this is wise) update the attributes explicitly then call save and pass false:
@model_name.attributes = params[:model_name] @model_name.save false
cattr_accessor_with_default
Class attribute assessors are neat if you want to set up modifiable constant-like varibles. This is how you’d normally set it up:
module MyPlugin class Conf @@awesome_level = 'huge' cattr_accessor :awesome_level end end
Then you can call and modify it like this:
>> MyPlugin::Conf.awesome_level => 'huge' >> MyPlugin::Conf.awesome_level = 'massive' >> MyPlugin::Conf.awesome_level => 'massive'
If you have a pile of those accessors I’d do something like this (there might be a better way, but it works):
module MyPlugin class Conf def self.cattr_accessor_with_default(name, value = nil) cattr_accessor name self.send("#{name}=", value) if value end cattr_accessor_with_default :awesome_level, 'huge' cattr_accessor_with_default :speed_level, 'insane' cattr_accessor_with_default :indifferent_level cattr_accessor_with_default :craziness_level, 'nuts' end end
This way you declare accessor and it’s optional default value on the same line
Keeping the flash object on multiple redirects
If your controllers are redirecting more than once, the flash contents will be lost. To avoid it, execute flash.keep before each redirection.
Check ActionController::Flash::FlashHash for more handy methods (discard, now, …)
Have the check_box checked by default
To have the check box checked by default, pass either :checked => true or :checked => 'checked' in the options. See ActionView::Helpers::InstanceTag#to_check_box_tag for details.
This is ON by default in :has_many
When defining a has_many relationship this behaviour is on by default. See has_many documentation, look for the :validate flag.
add index with :quiet=>true option for indices that are possibly already added
# Allows you to specify indices to add in a migration that will only be created if they do not # already exist, or to remove indices only if they already exist with :quiet=>true module ActiveRecord::ConnectionAdapters::SchemaStatements
def add_index_with_quiet(table_name, column_names, options = {}) quiet = options.delete(:quiet) add_index_without_quiet table_name, column_names, options rescue raise unless quiet and $!.message =~ /^Mysql::Error: Duplicate key name/i puts "Failed to create index #{table_name} #{column_names.inspect} #{options.inspect}" end alias_method_chain :add_index, :quiet def remove_index_with_quiet(table_name, column_names, options = {}) quiet = options.delete(:quiet) raise "no options allowed for remove_index, except quiet with this hack #{__FILE__}:#{__LINE__}" unless options.empty? remove_index_without_quiet table_name, column_names rescue raise unless quiet and $!.message =~ /^Mysql::Error: Can't DROP/i puts "Failed to drop index #{table_name} #{column_names.inspect}" end alias_method_chain :remove_index, :quiet
end
A catch-all format
If you’d like to specify a respond_to only for 1 or a few formats and render something else for all other formats, eg: (action.rss returns a feed but action.html or action.js should just render 404), use format.all:
respond_to do |format| format.rss { render_rss } format.all { render_404 } end
Rails will render an empty string for all formats that don’t specify a response explicitly.
ActiveRecord::RecordNotSaved can be triggered by accidental false return values in callbacks
You may have this exception raised if any of the defined callbacks such as ActiveRecord::Base#before_save or ActiveRecord::Base#before_create return false.
This can happen accidentally. For example:
class MyModel < ActiveRecord::Base before_save :assign_default_foo protected def assign_default_foo self.foo = false end end
Since assign_default_foo leaves a false value on the stack, the model will not be saved. A way around this is to simply leave nil or an empty return instead:
class MyModel < ActiveRecord::Base before_save :assign_default_foo protected def assign_default_foo self.foo = false nil end end
Writing and reading a cookie in the same request.
As of 0349278f3da9f7f532330cf295eed35ede3bae66 cookie updates will persist in the current request.
map_with_index
If you want to access the element index when using map, you can do it with enum_for:
(1..6).enum_for(:each_with_index).map { |v, i| "index: #{i} value: #{v}" } #=> ["index: 0 value: 1", "index: 1 value: 2", "index: 2 value: 3", "index: 3 value: 4", "index: 4 value: 5", "index: 5 value: 6"]
Equivalent to Array#reject!
This method is functionally identical to Array#reject!
Test if one array includes the elements of another
You can just use a set difference (aka minus) to see if one array includes all elements of another
not_included = [1,2,3] - (1..9).to_a not_included # => [] not_included = [1,2,3,'A'] - (1..9).to_a not_included # => ["A"]
Use intersection to test if any of the one are in the other:
shared = [1,2,3,'A'] & (1..9).to_a shared # => [1, 2, 3]
Tip: Define from_param(...) as Opposite
Often when defining a to_param method, it’s handy to introduce an opposite method for decoding them. For example:
class User < ActiveRecord::Base def self.from_param(param) find_by_name!(param) end def to_param name end end
While you can just as easily redefine the find() method, this may be confusing since the expectation is that find() works with numerical IDs, or whatever the key column is defined as.
A very thorough explanation of use
Ryan Daigle has a great article about 2.3’s new nest forms which does a really good job of explaining how to use this and some of the potential gotchas. Highly recommended:
http://ryandaigle.com/articles/2009/2/1/what-s-new-in-edge-rails-nested-attributes
Set :use_route to nil to let Rails pick the best route
Imagine the following case. You have two landing pages, one generic one, and an account specific one. The urls are as follows:
map.landing 'landing', :controller => 'landing', :action => 'index' map.account_landing 'accounts/:account_id/landing', :controller => 'landing', :action => 'index'
Now imagine you want a path to the landing page, using the most specific route possible. If you have an account_id, use it, if not, skip it.
You could do
url_for(:controller => 'landing', :action => 'index', :account_id => current_account)
If current_account is set you’ll get “/accounts/:account_id/landing” if not, you’ll get “/landing”. However, that just looks ugly.
Enter :use_route => nil.
landing_path(:account_id => nil) # => '/landing' landing_path(:account_id => 1) # => '/landing?account_id=1' landing_path(:account_id => nil, :use_route => nil) # => '/landing' landing_path(:account_id => 1, :use_route => nil) # => '/accounts/1/landing'
Setting :use_route to nil, is equivalent to the earlier #url_for example.
For the filename use File.basename
File.basename provides what File.dirname omits.
Argument Ordering
Be aware that the order of arguments for this method is the opposite of File.join:
File.expand_path('foo', '/bar') # => "/bar/foo" File.join('foo', '/bar') # => "foo/bar"
Handy shorthand for array manipulation
You may write something like this:
>> ['a', 'b', 'c'].collect{|letter| letter.capitalize} => ["A", "B", "C"]
But it looks so much nicer this way:
>> ['a', 'b', 'c'].collect(&:capitalize) => ["A", "B", "C"]
Format not coming out properly?
Date, Time and DateTime may have different formats defined.
If you do:
@user.created_at.to_formatted_s(:long_ordinal)
You will get (or something):
April 16th, 2009 22:03
But if you do:
@user.created_at.to_date.to_formatted_s(:long_ordinal)
You will get:
April 16th, 2009
So, be sure you know which one you are working with.