Dynamic exists? methods

szeryf Apr 22, 2010 2 thanks

There are no dynamic exists? methods analogous to dynamic finders, which means that while you can do this:

Person.find_by_name('David')

you can't do this:

Person.exists_by_name('David') # DOES NOT WORK

nor this:

Person.exists_by_name?('David') # DOES NOT WORK

However, you can simul...

Mode Flags

sshaw Apr 21, 2010

+RDONLY+, +TRUNC+, etc... are defined in the File::Constants module which is +include+'d by +IO+ and +File+.

IO.open fd, IO::RDONLY File.open path, File::RDONLY

Though as pointed out above, they are interchangeable.

Also behaves like File#expand_path

tadman Apr 16, 2010 1 thank

You can also use URI.join to resolve relative and absolute links:

URI.join('http://example.com/', '/example').to_s
# => "http://example.com/example"

URI.join('http://example.com/example', 'test').to_s
# => "http://example.com/test"

URI.join('http://example.com/example/', 'test...

Require file from the same folder

avakhov Apr 16, 2010 5 thanks

If you want to require file from the same folder, the simplest way is

require File.expand_path('../file-to-require', __FILE__)

If your file is /lib/book.rb

File.expand_path('../page', '/lib/book.rb') => '/lib/page.rb'

Careful with this method.

arronwashington Apr 3, 2010 3 thanks

Despite the name and description, it will actually update any changed fields on the model rather than just the desired attribute.

def update_attribute(name, value)
send(name.to_s + '=', value)
save(false)
end

See? Use update_all and pass in the model ID as a condition, instead.

Interpolating

bfcapell Mar 31, 2010 3 thanks

Note that to interpolate, the sequences must be inside single quotes: # replace /ll/ with itself 'hello'.gsub(/ll/, '\0') # returns 'hello' 'hello'.gsub(/ll/, "\0") # returns 'he\000o'

Wrong example

szeryf Mar 29, 2010

In the authentication filter example above, the time condition should be reversed: we only want to find the user if +time+ is still in the future (because it's the valid-until time).

So the example should look like this:

id, time = @verifier.verify(cookies[:remember_me])
if time > Time.no...

How to test callback methods

henning Mar 25, 2010

When testing callback methods, try to test the callback chain separate from its implementation.

Say this is your model:

class Project

belongs_to :owner
has_many :milestones

after_save :create_milestones
after_save :notify_owner

private

def notify_owner...