Permalink
Browse files

Allow a proc to be passed as the default value

It yields the enum class and lets you set the default value at runtime
  • Loading branch information...
beerlington committed Feb 8, 2013
1 parent 8987e79 commit 367aa0893d073b8043d4e80a395eaf5d2e7d9c40
Showing with 16 additions and 4 deletions.
  1. +8 −2 lib/classy_enum/active_record.rb
  2. +8 −2 spec/classy_enum/active_record_spec.rb
@@ -33,8 +33,14 @@ def classy_enum_attr(attribute, options={})
serialize_as_json = options[:serialize_as_json] || false
default = options[:default]
- if default.present? && !enum.include?(default)
- raise InvalidDefault, "must be one of [#{enum.to_a.join(',')}]"
+ if default.present?
+ if default.is_a? Proc
+ default = default.call(enum)
+ end
+
+ unless enum.include? default
+ raise InvalidDefault, "must be one of [#{enum.to_a.join(',')}]"
+ end
end
# Add ActiveRecord validation to ensure it won't be saved unless it's an option
@@ -162,11 +162,17 @@ class DefaultValueDog < Dog
end
describe DefaultValueDog do
- subject(:dog) { DefaultValueDog.new }
-
its(:breed) { should == :snoop }
end
+class DynamicDefaultValueDog < Dog
+ classy_enum_attr :breed, :default => lambda { |enum| enum.max }
+end
+
+describe DynamicDefaultValueDog do
+ its(:breed) { should == :husky }
+end
+
describe Dog, 'with invalid default value' do
it 'raises error with invalid default' do
expect {

0 comments on commit 367aa08

Please sign in to comment.