Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Adding support for default enum value

  • Loading branch information...
commit 4b9031a03a1595f906a5d8501d65121eec403532 1 parent 2aad064
@beerlington authored
View
11 lib/classy_enum/active_record.rb
@@ -1,4 +1,6 @@
module ClassyEnum
+ class InvalidDefault < StandardError; end
+
module ActiveRecord
# Class macro used to associate an enum with an attribute on an ActiveRecord model.
@@ -26,6 +28,11 @@ def classy_enum_attr(attribute, options={})
allow_blank = options[:allow_blank] || false
allow_nil = options[:allow_nil] || false
serialize_as_json = options[:serialize_as_json] || false
+ default = options[:default]
+
+ if default.present? && !default.in?(enum)
+ raise InvalidDefault, "must be one of [#{enum.to_a.join(',')}]"
+ end
# Add ActiveRecord validation to ensure it won't be saved unless it's an option
validates_inclusion_of attribute,
@@ -35,7 +42,9 @@ def classy_enum_attr(attribute, options={})
# Define getter method that returns a ClassyEnum instance
define_method attribute do
- enum.build(read_attribute(attribute),
+ value = read_attribute(attribute) || default
+
+ enum.build(value,
:owner => self,
:serialize_as_json => serialize_as_json,
:allow_blank => (allow_blank || allow_nil)
View
18 spec/classy_enum/active_record_spec.rb
@@ -157,6 +157,24 @@ class ActiveDog < Dog
end
+class DefaultValueDog < Dog
+ classy_enum_attr :breed, default: :snoop
+end
+
+describe DefaultValueDog do
+ subject(:dog) { DefaultValueDog.new }
+
+ its(:breed) { should == :snoop }
+end
+
+describe Dog, 'with invalid default value' do
+ it 'raises error with invalid default' do
+ expect {
+ Class.new(Dog) { classy_enum_attr :breed, default: :nope }
+ }.to raise_error(ClassyEnum::InvalidDefault)
+ end
+end
+
class Cat < ActiveRecord::Base
end
Please sign in to comment.
Something went wrong with that request. Please try again.