Browse files

Simplify .find and optimize its usage

  • Loading branch information...
1 parent af8f08a commit 59f63df4aa0315e36b264d09f18392bba4fdc5c3 @beerlington beerlington committed Aug 12, 2012
Showing with 7 additions and 9 deletions.
  1. +2 −4 lib/classy_enum/base.rb
  2. +5 −5 lib/classy_enum/collection.rb
View
6 lib/classy_enum/base.rb
@@ -57,12 +57,10 @@ def inherited(klass)
# Priority.build(:low) # => Priority::Low.new
# Priority.build(:invalid_option) # => :invalid_option
def build(value, options={})
- return value if value.blank? && options[:allow_blank]
+ object = find(value)
- # Return the value if it is not a valid member
- return value unless all.map(&:to_s).include? value.to_s
+ return value if object.nil? || (options[:allow_blank] && object.nil?)
- object = "#{base_class}::#{value.to_s.camelize}".constantize.new
object.owner = options[:owner]
object.serialize_as_json = options[:serialize_as_json]
object.allow_blank = options[:allow_blank]
View
10 lib/classy_enum/collection.rb
@@ -83,11 +83,11 @@ def each
# Priority.find('high') # => Priority::High.new
# Priority.find {|e| e.to_sym == :high } # => Priority::High.new
def find(key=nil)
- return super if block_given?
-
- key = build(key)
- return nil unless key.is_a?(ClassyEnum::Base)
- super { |e| e == key }
+ if block_given?
+ super
+ elsif map(&:to_s).include? key.to_s
+ super { |e| e.to_s == key.to_s }
+ end
end
alias detect find

0 comments on commit 59f63df

Please sign in to comment.