Class: Leeroy::Types::Enum
- Inherits:
-
TypesafeEnum::Base
- Object
- TypesafeEnum::Base
- Leeroy::Types::Enum
- Defined in:
- lib/leeroy/types/enum.rb
Overview
Implements the [Typesafe Enum pattern](www.oracle.com/technetwork/java/page1-139488.html#replaceenums). Implement your own classes that inherit from this.
Valid values for these enums must be Strings or otherwise stringifiable.
Usage: “‘ class EnumClass < Leeroy::Types::Enum
# 'foo' and 'bar' are the only acceptable values for EnumClass
new :FOO
new :BAR
end
enum_valid = Leeroy::Types::EnumClass.resolve(‘foo’) # returns a valid instance of Leeroy::Types::EnumClass::FOO enum_valid.to_s # returns ‘foo’ enum_invalid = Leeroy::Types::EnumClass.resolve(‘baz’) # raises an exception “‘
Class Method Summary collapse
- .from_s(x) ⇒ Object
-
.resolve(candidate, alternate = nil) ⇒ Object
Given a string or something that can be stringified, returns a subclass of the parent enum with a value matching the provided string.
Instance Method Summary collapse
Class Method Details
.from_s(x) ⇒ Object
60 61 62 |
# File 'lib/leeroy/types/enum.rb', line 60 def self.from_s(x) self.find_by_value_str(x.to_s) end |
.resolve(candidate, alternate = nil) ⇒ Object
Given a string or something that can be stringified, returns a subclass of the parent enum with a value matching the provided string.
Accepts an optional second argument; if the first argument cannot be resolved by the enum, the second argument will be resolved.
43 44 45 46 47 48 49 50 51 52 53 54 |
# File 'lib/leeroy/types/enum.rb', line 43 def self.resolve(candidate, alternate = nil) resolved = candidate.kind_of?(Leeroy::Types::Enum) ? candidate : self.from_s(candidate) if candidate.nil? resolved = self.resolve(alternate, nil) unless alternate.nil? end # FIXME raise some more appropriate type of error raise "invalid value for enum" if resolved.nil? resolved end |
Instance Method Details
#from_s(x) ⇒ Object
64 65 66 |
# File 'lib/leeroy/types/enum.rb', line 64 def from_s(x) self.from_s(x) end |
#resolve(candidate, alternate = nil) ⇒ Object
56 57 58 |
# File 'lib/leeroy/types/enum.rb', line 56 def resolve(candidate, alternate = nil) self.resolve(candidate, alternate) end |
#to_s ⇒ Object
32 33 34 |
# File 'lib/leeroy/types/enum.rb', line 32 def to_s self.value end |