Skip to content

Commit

Permalink
Updates to Avram Enums : ==, ===, enum constants (#566)
Browse files Browse the repository at this point in the history
* Implements == on Avram Enums

* implements case equality operator on avram_enum

Also provides named constants which reflect the underlying enum values

* convert enum charm to struct

* add sad-path specs for avram enum
  • Loading branch information
robacarp authored Dec 22, 2020
1 parent 90f0ab0 commit 26ff478
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 3 deletions.
40 changes: 40 additions & 0 deletions spec/type_extensions/enum_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,44 @@ describe "Enum" do
issue.status.to_s.should eq("Opened")
issue.status.to_i.should eq(0)
end

it "provides a working ==" do
Issue::Status.new(:closed).should eq(Issue::Status.new(:closed))
Issue::Status.new(:opened).should_not eq(Issue::Status.new(:closed))
end

it "provides enum-like constant values" do
Issue::Status::Closed.should eq(Issue::Status.new(:closed).enum)
Issue::Status.new(:closed).enum.should eq(Issue::Status::Closed)
end

it "implements case equality" do
case Issue::Status.new(:closed).value
when Issue::Status.new(:closed)
true
else
false
end.should be_true

case Issue::Status::Closed.value
when Issue::Status.new(:closed)
true
else
false
end.should be_true

case Issue::Status.new(:opened).value
when Issue::Status::Opened
true
else
false
end.should be_true

case Issue::Status::Opened.value
when Issue::Status::Opened
true
else
false
end.should be_true
end
end
19 changes: 16 additions & 3 deletions src/avram/charms/enum_extensions.cr
Original file line number Diff line number Diff line change
@@ -1,13 +1,26 @@
macro redeclare_avram_enum(name)
{% for member in name.resolve.constants %}
{{ member }} = {{ name }}::{{ member }}
{% end %}
end

macro avram_enum(enum_name, &block)
enum Avram{{ enum_name }}
{% avram_enum = ("Avram" + enum_name.names.join("::")).id %}
enum {{ avram_enum }}
{{ block.body }}

def ===(other : Int32)
value == other
end
end

class {{ enum_name }}
struct {{ enum_name }}
def self.adapter
Lucky
end

redeclare_avram_enum({{ avram_enum }})

getter :enum

# You may need to prefix with {{ @type }}
Expand All @@ -24,7 +37,7 @@ macro avram_enum(enum_name, &block)
@enum = Avram{{ enum_name }}.from_value(enum_value.to_i)
end

delegate to_s, to_i, to: @enum
delegate :===, to_s, to_i, to: @enum

forward_missing_to @enum

Expand Down

0 comments on commit 26ff478

Please sign in to comment.