Skip to content

Commit

Permalink
Adding support for default enum value
Browse files Browse the repository at this point in the history
  • Loading branch information
beerlington committed Feb 8, 2013
1 parent 2aad064 commit 4b9031a
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 1 deletion.
11 changes: 10 additions & 1 deletion lib/classy_enum/active_record.rb
Original file line number Diff line number Diff line change
@@ -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.
Expand Down Expand Up @@ -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,
Expand All @@ -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)
Expand Down
18 changes: 18 additions & 0 deletions spec/classy_enum/active_record_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down

0 comments on commit 4b9031a

Please sign in to comment.