Friday, April 18, 2008

ActsAsFerret and computed ferret fields

The ActsAsFerret plugin automatically indexes your model when saving.

The acts_as_ferret method takes a whole slew parameters which includes the fields to be indexed. For example say we have a User model:

 acts_as_ferret :fields => {    
:last_name => {:boost => 10,:store => :yes},
:first_name => {:boost => 1, :store => :yes},
:title => {:boost => 1, :store => :yes},
:introduction => {:boost => 10,:store => :yes}
}, :ferret => {:or_default => true}, :remote => true


This will add last_name, first_name, title and introduction to the index. These fields are just database columns. The symbol for field is really just a method call and so this how we can add computed or nested ferret fields for indexing.

Suppose the user has a set tags with a simple 'has_many :tags' declaration.

Then we can create a simple method in the user model like this.
def user_tags
tags.map(&:name).join(',')
end


and add this method(field) to the acts_as_ferret method

  acts_as_ferret :fields => {    
:last_name => {:boost => 10,:store => :yes},
:first_name => {:boost => 1, :store => :yes},
:title => {:boost => 1, :store => :yes},
:introduction => {:boost => 10,:store => :yes},
:user_tags => {:boost => 10,:store => :yes}
}, :ferret => {:or_default => true}, :remote => true


Now we have the user's tags in the User index.

Friday, April 11, 2008

Quick Tip - extract_options!

ActiveSupport added a helpful method named 'extract_options!' that

"Extracts options from a set of arguments. Removes and returns the last element in the array if it‘s a hash, otherwise returns a blank hash."

So when we have a method that can accept multiple attributes the last of which could be a hash of options, instead of doing...

def some_method(*attributes)
configuration = {
:some_default => 'value'
}
configuration.update(attributes.pop) if attributes.last.is_a?(Hash)
.......
end

We have the more elegant...


def some_method(*attributes)
configuration = {
:some_default => 'value'
}
configuration.update(attributes.extract_options!)
.......
end

Wednesday, April 9, 2008

Missing host to link to! Please provide :host parameter or set default_url_options[:host]

When using a link_to or url_for in an ActionMailer and you need to set the host.

In production.rb or the appropriate env config file.

config.action_mailer.default_url_options = { :host => 'www.example.com' }