A method for restricting an attribute to a set of choices.
An invocation of attr_enumerator will create:
-
A validation requiring the attribute value to be one of the provided choices
-
A class constant containing all valid choices
-
Instance methods for each choice, returning
trueif the attribute is that value andfalseotherwise -
Scopes for each choice that retrieve records where the attribute is that value (only applicable when used with
ActiveRecord)
class Car < ActiveRecord::Base attr_enumerator :color, ['red', 'blue'] end car = Car.new car.color = 'red' car.color_red? # => true car.color_blue? # => false Car::COLORS # => ['red', 'blue'] car.save Car.color_red # => [<#Car>] car.color = 'green' car.valid? # => false car.errors # => #<OrderedHash {:color=>["is invalid"]}>
The AttrEnumerator module is automatically included in ActiveRecord::Base and is available for use in all ActiveRecord models.
To use attr_enumerator on a non-ActiveRecord model the class must include ActiveModel::Validations and provide an accessor to the attribute.
class Car include ActiveModel::Validations include AttrEnumerator attr_accessor :color attr_enumerator :color, ['red', 'blue'] end
An options hash may be passed as the last argument to attr_enumerator to configure its behavior. For example:
class Car < ActiveRecord::Base attr_enumerator :color, ['red', 'blue'], :constant => :PAINT_COLORS, :prefix => :colored end Car::PAINT_COLORS # => ['red', 'blue'] car = Car.new car.color = 'red' car.colored_red? # => true
-
constant(default: pluralized, uppercased attribute name)Set a custom constant name.
-
prefix(default: attribute name)Set a custom prefix for methods and scopes. Set to
falseto disable. -
message(default: internationalized"is invalid")Set the validation error message when the attribute is not a valid value. Use
%{value}to refer to the value of the attribute, e.g."%{value} is not a valid choice". -
allow_nil(default:false)Allow the attribute to be
nil. -
allow_blank(default:false)Allow the attribute to be blank.
-
if(default: unused)Set a method, proc or string to call to determine if the validation should occur. See
ActiveModel::Validationsfor more details. -
unless(default: unused)Set a method, proc or string to call to determine if the validation should not occur.
-
Check out the latest master to make sure the feature hasn’t been implemented or the bug hasn’t been fixed yet
-
Check out the issue tracker to make sure someone already hasn’t requested it and/or contributed it
-
Fork the project
-
Start a feature/bugfix branch
-
Commit and push until you are happy with your contribution
-
Make sure to add tests for it. This is important so I don’t break it in a future version unintentionally.
-
Create a pull request
-
Let me know if you want to be included in CONTRIBUTORS.txt