Christos Zisopoulos
2009-Sep-14 13:30 UTC
Gauging interest in an ActiveRecord attributes choices feature
Seeing as a lot of big changes are going into Rails 3, I thought this
might be an opportune time to try and squeeze a small feature into
ActiveRecord.
What I am proposing is support for mapping ActiveRecord attribute
values to display values for consumption by humans.
Quick example:
class User < ActiveRecord::Base
attr_choices :gender, { ''m'' => "Male",
''f'' => ''Female''}
end
>> @john = User.new(:name => ''John'', :gender =>
''m'')
>> @john.gender
=> ''m''
>> @john.gender_display # generated by the attr_choices macro
=> ''Male''
>> User.gender_choices # for use in select helpers
=> [["Male", ''m''],
[''Female'', ''f'']]
This facility already exists in at least one more framework that I
know of (Django). It is a very common pattern that I often see
implemented with custom model methods or by using view helpers. As
such, I believe it has a place in the core.
I use it as as a plugin[1] with all of my projects but what I wanted
to do is ask here if there is any interest in porting it to the core.
The plugin already supports I18n and validations of inclusion and I
believe it can be used to provide default values to the select helper
without explicitly specifying it:
<!-- implied gender_choices as second parameter -->
<%= f.select :gender %>
Cheers!
-christos
[1] http://github.com/christos/attribute_choices/tree