Skip to content

Commit

Permalink
Enum string parsing (#639)
Browse files Browse the repository at this point in the history
* Treat string enum values as their to_s representation

* Try to coerce to an integer first, then try parsing

A valid enum value name can't start with a digit, so theoretically this is safe.
Integers will only have digits (and a leading digit), so the two are mutually exclusive.

* Add tests for parsing enum values
  • Loading branch information
icy-arctic-fox authored Feb 24, 2021
1 parent 8c6aba6 commit 1fc856f
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
10 changes: 10 additions & 0 deletions spec/type_extensions/enum_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ describe "Enum" do
Issue::Status.new(:closed).enum.should eq(Issue::Status::Closed)
end

it "parses the enum value name" do
Issue::Status.new("Closed").should eq(Issue::Status.new(:closed))
Issue::Status.new("Opened").should eq(Issue::Status.new(:opened))
end

it "parses the enum value integer when a string" do
Issue::Status.new("0").should eq(Issue::Status.new(:opened))
Issue::Status.new("1").should eq(Issue::Status.new(:closed))
end

it "implements case equality" do
case Issue::Status.new(:closed).value
when Issue::Status.new(:closed)
Expand Down
9 changes: 7 additions & 2 deletions src/avram/charms/enum_extensions.cr
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,12 @@ macro avram_enum(enum_name, &block)
end

def initialize(enum_value : String)
@enum = Avram{{ enum_name }}.from_value(enum_value.to_i)
int_value = enum_value.to_i?
@enum = if int_value
Avram{{ enum_name }}.from_value(int_value)
else
Avram{{ enum_name }}.parse(enum_value)
end
end

delegate :===, to_s, to_i, to: @enum
Expand All @@ -58,7 +63,7 @@ macro avram_enum(enum_name, &block)
end

def parse(value : String)
SuccessfulCast({{ enum_name }}).new({{ enum_name }}.new(value.to_i))
SuccessfulCast({{ enum_name }}).new({{ enum_name }}.new(value))
end

def parse(value : Int32)
Expand Down

0 comments on commit 1fc856f

Please sign in to comment.