Flowdock

Recent notes

RSS feed
March 4, 2010
1 thank

AASM named scopes

If you are using the aasm plugin/gem, this will generate all named scopes for your various states.

Code example

Class Article <  ActiveRecord::Base

  include AASM

  aasm_initial_state :created

  aasm_state :published
  aasm_state :unpublished
  aasm_state :deleted
  aasm_state :created

  aasm_event :publish do
    transitions :to => :published, :from => [:created]
  end

  aasm_event :unpublish do
    transitions :to => :unpublished, :from => [:created, :published]
  end

  aasm_event :delete do
    transitions :to => :deleted, :from => [:published, :unpublished]
  end

  aasm_states.each { |s| named_scope s, :conditions => { :state => s.to_s } }  

end
March 4, 2010 - (>= 1.2.8)
5 thanks

stub_chain is very useful when testing controller code

or any other chained method call type that you’d like to stub, example:

in your controller:

def new
  @user = current_site.users.new
end

in your spec:

it "#new should assign a @user" do 
  u = mock("User")
  controller.stub_chain(:current_site, :users, :new).and_return(u)
  assigns[:user].should == u
end

whereas before you had to stub each chained method call separately:

it "#new should assign a @user" do 
  u = mock("User")
  users = mock("Users collection", :new => u)
  site = mock("Site", :users => users)
  controller.stub!(:current_site).and_return(site)
  assigns[:user].should == u
end

Please note that stub_chain was added to RSpec in version 1.2.6

March 4, 2010
3 thanks

Re: Caveat when using dynamic layouts

Since there’s no way to edit posts on here, I need to correct myself and say that what I posted before doesn’t work, since you can’t specify layout multiple times:

class OrdersController < BaseController
  layout :determine_layout, :only => :new
  layout "public", :except => :new
  # ...
end

So don’t do that. The only way to ensure that the other actions get the default theme is to drop :only/:except and do the conditions yourself:

class OrdersController < BaseController
  layout :determine_layout

private
  def determine_layout
    %w(new).include?(action_name) ? "some_layout" : "public"
  end
end

All this to say, beware of :only/:except – they aren’t as useful as you think they are.

March 3, 2010
3 thanks

Deprecated in 1.9.x!

Use FileUtils::copy instead. It is also in 1.8.x, FileUtils, so call that one instead.

March 3, 2010 - (>= v1_8_6_287)
4 thanks

makedirs(path) to create file path

mkdir will only create a single directory on an existing path. If you want to create a full path, like the `mkdir -p /full/path` command, use the makedirs method.

1.8: File.makedirs(path) 1.9: FileUtils.makedirs(path)

February 27, 2010
4 thanks

Caveat when using dynamic layouts

Worth noting that if you have a controller which inherits from another controller which has a layout, and in this child controller you’re determining the layout at runtime using a method for specific actions, the other actions you are excluding will not inherit the layout from the parent controller.

For example, if you’ve got this

class BaseController < ApplicationController
  layout "public"
end
class OrdersController < BaseController
  layout :determine_layout, :only => :new
  # index, show, new, create, edit, update, destroy ...
end

then OrdersController#index, #show, and #edit won’t get the “public” layout – in fact they won’t get a layout at all. So you’ll need to do this instead:

class OrdersController < BaseController
  layout :determine_layout, :only => :new
  layout "public", :except => :new
  # ...
end
February 26, 2010
3 thanks

default_scope on create

If you specify :conditions in your default_scope in form of a Hash, they will also be applied as default values for newly created objects. Example:

class Article
  default_scope :conditions => {:published => true}
end

Article.new.published? # => true

However:

class Article
  default_scope :conditions => 'published = 1'
end

Article.new.published? # => false
February 25, 2010
2 thanks

configuration no longer in environment.rb

configure session store in config/initializers/session_store.rb

February 25, 2010
1 thank

Saving other objects inside before_save

Don’t call .save or .update_attribute on other objects inside before_save callback.

Saving other objects inside of before_save callback results in flushing changed hash and the original object is not updated.

UPDATE observed sometimes, still investigating

February 25, 2010
1 thank

Redirect...

See ActiveRecord::ConnectionAdapters::TableDefinition#column for details of the options you can use.

February 25, 2010
2 thanks

Possible gotcha

This method returns a Pathname object which handles paths starting with a / as absolute (starting from the root of the filesystem). Compare:

>> Rails.root
=> #<Pathname:/some/path/to/project>
>> Rails.root + "file"
=> #<Pathname:/some/path/to/project/file>
>> Rails.root + "/file"
=> #<Pathname:/file>
>> Rails.root.join "file"
=> #<Pathname:/some/path/to/project/file>
>> Rails.root.join "/file"
=> #<Pathname:/file>
February 25, 2010
0 thanks

See documentation for the class method

Since Rails version 2, this instance method no longer exists.

You may be looking for its namesake class method, ActiveRecord::Base.method_missing

February 23, 2010
3 thanks

Easy workaround for missing :through option

Note that belongs_to does not support :through option like has_many (although IMHO it would make sense in some cases), but you can easily simulate it with delegate.

For example:

class Person < ActiveRecord::Base
  belongs_to :team
  ...
end
class Task < ActiveRecord::Base
  belongs_to :person
  delegate :team, :to => :person
end

There is of course more ways to do it, but this seems to be the easiest to me.

February 23, 2010
0 thanks

note: the example format regex is too lenient

The example regex for RFC 2822 email is too lenient. Sure it’s just an example, but it wound up in our code and we just had to fix it to match the RFC.

The regex as given allows any non-@ non-whitespace characters. But the RFC only allows these characters in mailbox names

alpha digit - ! \ # $ % & ' * + \ / = ? ^ _ ` { | } ~ ] +

and . is only allowed between atoms of 1 or more of the above.

Here’s the corrected regex:

:with => /\A([-a-z0-9!\#$%&'*+\/=?^_`{|}~]+\.)*[-a-z0-9!\#$%&'*+\/=?^_`{|}~]+@((?:[-a-z0-9]+\.)+[a-z]{2,})\Z/i
February 19, 2010
8 thanks

Hash#except

Note that the ActiveSupport library provides the except and except! methods, which return the Hash minus the given keys. So you don’t need to write your own wrapper if you happen to be using Rails or ActiveSupport as a stand-alone library:

http://apidock.com/rails/ActiveSupport/CoreExtensions/Hash/Except/except

February 16, 2010
0 thanks

Re: POST DATA

The ampersand is more common, but the W3C recommends that all web servers support semicolon separators in the place of ampersand separators:

http://www.w3.org/TR/1999/REC-html401-19991224/appendix/notes.html#h-B.2.2

February 16, 2010 - (>= v2.1.0)
3 thanks

Extract the aggregated scoping options

If you want to get the aggregated scoping options of a chain of named scopes use ActiveRecord::Base.current_scoped_methods

It works in the fashion of:

Shirt.red.medium.alphabetical.current_scoped_methods
# ==>
{
  :create => {}, 
  :find => {
    :conditions => {:color => 'red', :size => 'medium'}, 
    :order => 'shirts.name ASC'
  } 
}
February 12, 2010
0 thanks

Example

Delete all files in log

require 'FileUtils'
FileUtils.rm_rf(Dir.glob("log/*"))
February 12, 2010
1 thank

re: Options

@ramanavel - The options are dependent on the cache store that you’re using. You’ll need to have a look at what the cache store you’re using allows.

e.g. MemCacheStore allows the use of time criteria based :expires_in, most of the cache stores don’t.

http://guides.rubyonrails.org/caching_with_rails.html might provide a little more information.

February 11, 2010 - (v1_8_6_287 - v1_8_7_72)
1 thank

Using Unshift with Load Path's

Using unshift on your load path’s for Rails, Sinatra, etc, is a good way of ensuring that the file your including is going to be first.

Example

vendor = File.join(File.dirname(__FILE__), 'vendor')
$LOAD_PATH.unshift File.expand_path(File.join(vendor, 'ultraviolet-0.10.5',  'lib'))
February 11, 2010 - (v1_8_7_72)
0 thanks

Odd Number of padding characters

In the case of an odd number of empty spaces in a length, Ruby will append the extra character to the right-hand side of the string.

Example:

irb(main):002:0> "Hello".center(10,"-")
=> "--Hello---"
February 11, 2010 - (v1_8_6_287 - v1_8_7_72)
0 thanks

Clarification of argument

The description should read:

The argument is the salt string, which must be at least two characters long, each character drawn from [a-zA-Z0-9./].

February 11, 2010
4 thanks

reload equivalent for models

The reset_column_information method provides a similar function for the model itself. Most useful during migrations.

February 9, 2010
0 thanks

Options

What are all the options here please?…

February 5, 2010
2 thanks

the :order parameter is not sanitized

The :order parameter is not sanitized, so doing something like Person.find( :first , :order => params[:order] ) could get you in trouble.

February 5, 2010
2 thanks

An alternate way to have a string ID as a primary key

You can disable automatically created primary key and add it to manually with mysql:

The migration file:

def self.up

  create_table( :my_special_table, :id => false ) do |t|
    t.string :id, :limit => 5, :null => :no
  end

  execute "ALTER TABLE my_special_table ADD PRIMARY KEY (id)"

end

Then in a before_save filter you can generate the primary key for yourself.

Use a transaction and be aware of uniqueness!

February 5, 2010
3 thanks

Rmoving preceding 0's

In most *nix system, adding a - after the % will remove preceding 0s.

So %-d for a single digit day, or %-I for a single digit hour, etc.

February 4, 2010 - (>= v2.1.0)
1 thank

All dates in the database are stored in UTC and all dates in Ruby are in a local timezone

With the timezone support introduced in Rails 2.1 the idea is that all dates in the database are stored in UTC and all dates in Ruby are in a local timezone.

Time.zone.now == Time.now # => false

as Peter Marklund lights up this in his blog:

http://marklunds.com/articles/one/402

“They will only be converted to UTC for you if they are ActiveSupport::TimeWithZone objects, not if they are Time objects. This means that you are fine if you use Time.zone.now, 1.days.ago, or Time.parse(”2008-12-23“).utc, but not if you use Time.now or Time.parse(”2008-12-23“)”

February 4, 2010
1 thank

Warning! Be aware of Active Record TimeZone

With the timezone support introduced in Rails 2.1 the idea is that all dates in the database are stored in UTC and all dates in Ruby are in a local timezone.

Time.zone.now == Time.now # => false

http://marklunds.com/articles/one/402