Skip to content

Commit

Permalink
Enum classes should have types (#67)
Browse files Browse the repository at this point in the history
  • Loading branch information
joeldrapper authored Dec 12, 2023
1 parent b3e3a18 commit b397acc
Show file tree
Hide file tree
Showing 4 changed files with 18 additions and 25 deletions.
11 changes: 7 additions & 4 deletions lib/literal/constructors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@
module Literal::Constructors
SpecialisedEnums = {
String => Class.new(Literal::Enum) do
def type = String
@type = String

alias_method :to_s, :value
alias_method :to_str, :value
end,

Integer => Class.new(Literal::Enum) do
def type = Integer
@type = Integer

alias_method :to_i, :value
end,

Array => Class.new(Literal::Enum) do
def type = Array
@type = Array

alias_method :to_a, :value
alias_method :to_ary, :value
end
Expand All @@ -27,7 +30,7 @@ def Array(type)

def Enum(type)
SpecialisedEnums[type] || Class.new(Literal::Enum) do
define_method(:type) { type }
@type = type
end
end

Expand Down
7 changes: 7 additions & 0 deletions lib/literal/enum.rb
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,12 @@ def respond_to_missing?(name, include_private = false)
end

def inherited(subclass)
type = @type

subclass.instance_exec do
@values = {}
@members = []
@type = type
end
end

Expand Down Expand Up @@ -96,6 +99,10 @@ def name
"#{self.class.name}::#{@name}"
end

def type
self.class.type
end

alias_method :inspect, :name

def siblings
Expand Down
21 changes: 0 additions & 21 deletions lib/literal/enum_type.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,25 +12,4 @@ def inspect
def ===(value)
Literal::Enum === value && value.type == @type
end

def define(&)
type = @type

Class.new(Literal::Enum) do
@type = type

if Integer == type
alias_method :to_i, :value
elsif String == type
alias_method :to_s, :value
elsif Array == type
alias_method :to_a, :value
elsif Hash == type
alias_method :to_h, :value
end

class_exec(&)
deep_freeze
end
end
end
4 changes: 4 additions & 0 deletions test/literal/enum.test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,10 @@ def toggle = Switch::On
assert Color.frozen?
end

test "the enum class has a type" do
expect(Color.type) == Integer
end

test "the enum class is enumerable" do
expect(Color).to_be_an Enumerable
expect(Color.map(&:value)) == [0, 1, 3, 4]
Expand Down

0 comments on commit b397acc

Please sign in to comment.