Class: Appear::Util::ValueClass
- Inherits:
-
Object
- Object
- Appear::Util::ValueClass
- Defined in:
- lib/appear/util/value_class.rb
Overview
An immutable value type, similar to Struct, but with annotated attr_readers, that can be easily created from a Hash with the necessary fields.
Direct Known Subclasses
Defined Under Namespace
Classes: MissingValueError
Class Method Summary collapse
-
.properties ⇒ Array<Symbol>
Names of all properties.
-
.property(name, opts = {}) ⇒ Object
Define an attribute reader that can be populated by the constructor.
Instance Method Summary collapse
-
#initialize(data) ⇒ ValueClass
constructor
A new instance of ValueClass.
Constructor Details
#initialize(data) ⇒ ValueClass
Returns a new instance of ValueClass.
14 15 16 17 18 19 20 21 22 |
# File 'lib/appear/util/value_class.rb', line 14 def initialize(data) self.class.properties.each do |val| begin instance_variable_set("@#{val}", data.fetch(val)) rescue KeyError raise MissingValueError.new("#{self.class.name}: no value for attribute #{val.inspect}") end end end |
Class Method Details
.properties ⇒ Array<Symbol>
Returns names of all properties.
46 47 48 49 50 51 52 53 |
# File 'lib/appear/util/value_class.rb', line 46 def self.properties @props ||= [] if self.superclass.respond_to?(:properties) self.superclass.properties + @props else @props end end |
.property(name, opts = {}) ⇒ Object
Define an attribute reader that can be populated by the constructor.
33 34 35 36 37 38 39 40 41 42 43 |
# File 'lib/appear/util/value_class.rb', line 33 def self.property(name, opts = {}) var_name = opts.fetch(:var, name) @props ||= [] @props << var_name # we could do super, but we want to allow defining :acttive? or so class_eval "def #{name}; @#{var_name}; end" var_name end |