attr_enumerator
A method for restricting an attribute to a set of choices.
An invocation of attr_enumerator
will create:
-
a class constant containing all valid choices
-
a validation requiring the attribute’s value to be one of the choices
-
instance methods for each choice, returning
true
if the attribute is that value andfalse
otherwise -
scopes for each choice that retrieve records where the attribute is that value
Example
class Car < ActiveRecord::Base
attr_enumerator :color, ['red', 'blue']
end
# constant
Car::COLORS # => ['red', 'blue']
# validation
car = Car.new
car.color = 'green'
car.valid? # => false
car.errors # => {:color => ["is invalid"]}
car.color = 'red'
car.valid? # => true
# instance methods
car.red? # => true
car.blue? # => false
# scopes
car.save
Car.red # => [<#Car>]
With or without ActiveRecord
The AttrEnumerator
module will be automatically included in ActiveRecord::Base
, making the attr_enumerator
method available in all ActiveRecord models.
To include AttrEnumerator
on a non-ActiveRecord model the class must also include ActiveModel::Validations
and provide an accessor to the attribute. The model will have all the above functionality except no scopes will be generated.
class Car
include ActiveModel::Validations
include AttrEnumerator
attr_accessor :color
attr_enumerator :color, ['red', 'blue']
end
Configuration
Options 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 => :painted
end
Car::PAINT_COLORS # => ['red', 'blue']
car = Car.new
car.color = 'red'
car.painted_red? # => true
Options
-
constant
(default: pluralized, uppercased attribute name)Set a custom constant name.
-
prefix
(default:nil
)Set a prefix for generated methods and scopes.
-
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
/allow_blank
(default:false
)Do not fail validation when the attribute is
nil
or blank. -
if
/unless
(default: unused)Set a method, proc or string to call to determine if the validation should occur. See
ActiveModel::Validations
for more details.
Contributing to attr_enumerator
-
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