Skip to content

Commit

Permalink
Showing 2 changed files with 24 additions and 7 deletions.
13 changes: 12 additions & 1 deletion spec/std/enum_spec.cr
Original file line number Diff line number Diff line change
@@ -8,6 +8,7 @@ end

enum SpecEnum2
FourtyTwo
FOURTY_FOUR
end

@[Flags]
@@ -104,7 +105,17 @@ describe Enum do
SpecEnum.parse("Two").should eq(SpecEnum::Two)
SpecEnum2.parse("FourtyTwo").should eq(SpecEnum2::FourtyTwo)
SpecEnum2.parse("fourty_two").should eq(SpecEnum2::FourtyTwo)
expect_raises(Exception, "Unknown enum SpecEnum value: Four") { SpecEnum.parse("Four") }
expect_raises(ArgumentError, "Unknown enum SpecEnum value: Four") { SpecEnum.parse("Four") }

SpecEnum.parse("TWO").should eq(SpecEnum::Two)
SpecEnum.parse("TwO").should eq(SpecEnum::Two)
SpecEnum2.parse("FOURTY_TWO").should eq(SpecEnum2::FourtyTwo)

SpecEnum2.parse("FOURTY_FOUR").should eq(SpecEnum2::FOURTY_FOUR)
SpecEnum2.parse("fourty_four").should eq(SpecEnum2::FOURTY_FOUR)
SpecEnum2.parse("FourtyFour").should eq(SpecEnum2::FOURTY_FOUR)
SpecEnum2.parse("FOURTYFOUR").should eq(SpecEnum2::FOURTY_FOUR)
SpecEnum2.parse("fourtyfour").should eq(SpecEnum2::FOURTY_FOUR)
end

it "parses?" do
18 changes: 12 additions & 6 deletions src/enum.cr
Original file line number Diff line number Diff line change
@@ -338,21 +338,27 @@ struct Enum
# end

# Returns the enum member that has the given name, or
# raises if no such member exists. The comparison is made by using
# `String#camelcase` between *string* and the enum members names.
# raises `ArgumentError` if no such member exists. The comparison is made by using
# `String#camelcase` and `String#downcase` between *string* and
# the enum members names, so a member named "FourtyTwo" or "FOURTY_TWO"
# is found with any of these strings: "fourty_two", "FourtyTwo", "FOURTY_TWO",
# "FOURTYTWO", "fourtytwo".
#
# ```
# Color.parse("Red") # => Color::Red
# Color.parse("BLUE") # => Color::Blue
# Color.parse("Yellow") # => Exception
# ```
def self.parse(string) : self
parse?(string) || raise "Unknown enum #{self} value: #{string}"
parse?(string) || raise ArgumentError.new("Unknown enum #{self} value: #{string}")
end

# Returns the enum member that has the given name, or
# `nil` if no such member exists. The comparison is made by using
# `String#camelcase` between *string* and the enum members names.
# `String#camelcase` and `String#downcase` between *string* and
# the enum members names, so a member named "FourtyTwo" or "FOURTY_TWO"
# is found with any of these strings: "fourty_two", "FourtyTwo", "FOURTY_TWO",
# "FOURTYTWO", "fourtytwo".
#
# ```
# Color.parse?("Red") # => Color::Red
@@ -361,9 +367,9 @@ struct Enum
# ```
def self.parse?(string) : self?
{% begin %}
case string.camelcase
case string.camelcase.downcase
{% for member in @type.constants %}
when {{member.stringify.camelcase}}
when {{member.stringify.camelcase.downcase}}
{{@type}}::{{member}}
{% end %}
else

0 comments on commit 46303f5

Please sign in to comment.