sferik/rails_admin — Issue #773: Support enumerated_attribute
Author: turadg
Created: 2011-10-12 19:47:00+00:00
State: open

This is a feature request. I tried implementing it myself but got stuck. I want to see if a patch would be accepted to do this, or if anyone else would implement it more easily.

[enumerated_attribute](https://github.com/jeffp/enumerated_attribute) is a gem for creating enumerated fields on objects. It integrates with ActiveRecord but uses different method names such that rails_admin doesn't notice them.

Here's an example:
```
t=Tractor.new
e = t.enums(:plow) # => [:up, :down]
e.labels # => ['Up', 'Down']
e.hash # => {:up=>'Up', :down=>'Down'}
e.select_options # => [['Up', 'up'], ['Down', 'down']]
e.label(:up) # => 'Up'
```

Rails Admin would check `respond_to?(:plow_enum)`, putting the attribute in the method name, but enumerated_attribute's convention for the same is `object.enums(:plow)`. I tried adding this to `enum.rb` with:
```
register_instance_option(:enum) do
if bindings[:object].respond_to?("enums")
bindings[:object].send('enums', self.name)
else
bindings[:object].send(self.enum_method)
end
end
```

But it never passes this test I added in `rails_admin_config_edit_spec.rb`:
```
it "should auto-detect enumeration when object responds to 'enums(\#{method})'" do
class Team
def enums attribute_name
puts "#{self.class} object.enums called with #{attribute_name}"
["blue", "green", "red"] if attribute_name.to_sym == :color
end
end
RailsAdmin.config Team do
edit do
field :color
end
end
visit new_path(:model_name => "team")
should have_selector("select.enum")
should have_content("green")
Team.send(:remove_method, :enums) # Reset
end
```

The enums() method gets called and returns the correct value, but the select doesn't end up rendering.

I see a case for adding support for Rails Admin to `enumerated_attribute` rather than vice-versa, but if support were added to Rails Admin, it would work for all the existing users of `enumerated_attribute` instead of requiring an upgrade and creating duplicate functionality (of `aname_enum` and `enums(:aname)`).