Class: AnotherEnum
- Inherits:
-
Object
- Object
- AnotherEnum
- Defined in:
- lib/another_enum.rb
Overview
Provide support for defining enumerated types.
Example
class Colour < AnotherEnum
define :red do
# ...
end
define :green do
# ...
end
define :blue do
# ...
end
end
Class Method Summary collapse
- .all ⇒ Object
- .codes ⇒ Object
-
.define(code, &block) ⇒ Object
Public: Declare a enumerated value.
- .fetch(code) ⇒ Object
- .get(arg) ⇒ Object (also: [])
-
.hardcode(attributes) ⇒ Object
Public: Succintly declare methods to return hardcoded values.
Instance Method Summary collapse
Class Method Details
.all ⇒ Object
80 81 82 |
# File 'lib/another_enum.rb', line 80 def all @all_by_code.values end |
.codes ⇒ Object
84 85 86 |
# File 'lib/another_enum.rb', line 84 def codes @all_by_code.keys end |
.define(code, &block) ⇒ Object
Public: Declare a enumerated value.
code - a unique (String) code that identifies this value block - optional block defines behaviour specific to this value
Example
class Colour < AnotherEnum; end
Colour.define :red do
def rgb
"#ff0000"
end
end
44 45 46 47 48 |
# File 'lib/another_enum.rb', line 44 def define(code, &block) code = code.to_sym.to_s value = generate_value(code, &block) register_value(code, value) end |
.fetch(code) ⇒ Object
76 77 78 |
# File 'lib/another_enum.rb', line 76 def fetch(code) get(code) || raise(ArgumentError, "no such #{self}: #{code.inspect}") end |
.get(arg) ⇒ Object Also known as: []
69 70 71 72 |
# File 'lib/another_enum.rb', line 69 def get(arg) return arg if self === arg @all_by_code[arg.to_s] end |
.hardcode(attributes) ⇒ Object
Public: Succintly declare methods to return hardcoded values.
attributes - a Hash; a method will be generated for each key, returning
the corresponding value
Example
Colour.define :red do
hardcode :rgb => "#ff0000"
end
63 64 65 66 67 |
# File 'lib/another_enum.rb', line 63 def hardcode(attributes) attributes.each do |name, value| define_method(name) { value } end end |
Instance Method Details
#inspect ⇒ Object
113 114 115 |
# File 'lib/another_enum.rb', line 113 def inspect "#{self.class}.#{code}" end |
#to_s ⇒ Object
109 110 111 |
# File 'lib/another_enum.rb', line 109 def to_s code end |