zilkey/active_hash — pull request #56 by jmonteiro (2012-10-06 18:05:35+00:00)
Title: Direct name association

I used "EnumRecords" Rails plugin (I think it's for Rails 1.x and 2.x) for a long time, and got used to setting my enumeration associations using an easy-to-remember string. With that in mind, I adapted it to work with ActiveHash.

From the readme:

-------

### Using shortcuts

Since ActiveHashes usually are static, we can use shortcuts to assign via an easy to remember string instead of an obscure ID number.

# app/models/country.rb
class Country < ActiveHash::Base
end

# app/models/person.rb
class Person < ActiveRecord::Base
extend ActiveHash::Associations::ActiveRecordExtensions
belongs_to_active_hash :country, :shortcuts => [:name]
end

# config/initializers/data.rb
Country.data = [
{:id => 1, :name => "US"},
{:id => 2, :name => "Canada"}
]

# Using `rails console`
john = Person.new
john.country_name = "US"
# Is the same as doing `john.country = Country.find_by_name("US")`
john.country_name
# Will return "US", and is the same as doing `john.country.try(:name)`

You can have multiple shortcuts, so settings `:shortcuts => [:name, :friendly_name]` will enable you to use `#country_name=` and `#country_friendly_name=`.