Skip to content

Commit

Permalink
Simplify .find and optimize its usage
Browse files Browse the repository at this point in the history
  • Loading branch information
beerlington committed Aug 12, 2012
1 parent af8f08a commit 59f63df
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 9 deletions.
6 changes: 2 additions & 4 deletions lib/classy_enum/base.rb
Expand Up @@ -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]
Expand Down
10 changes: 5 additions & 5 deletions lib/classy_enum/collection.rb
Expand Up @@ -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
Expand Down

0 comments on commit 59f63df

Please sign in to comment.