Class: HashObject::Element
- Inherits:
-
Object
- Object
- HashObject::Element
- Defined in:
- lib/hash_object.rb
Overview
An internal object that records the state of the mapping between individual keys in a hash object and the actual methods that need to be created.
Instance Attribute Summary collapse
-
#name ⇒ Symbol
readonly
Sym The name that is to be parsed from the Hash, if it is not the symbol name.
-
#sym ⇒ Symbol
readonly
Sym The name of the method.
Instance Method Summary collapse
-
#default_value ⇒ Object
An abstraction around the default value of the object, whether it is a reified object or a Proc that will generate the default value.
-
#initialize(sym, options) ⇒ Element
constructor
Creates an element mapping.
-
#set(obj, value) ⇒ Object
Sets the value of the newly created element, either parsing the value, setting the default, or using the builder.
-
#set_default(obj) ⇒ nil
Sets the default value of the object.
Constructor Details
#initialize(sym, options) ⇒ Element
Creates an element mapping.
50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 |
# File 'lib/hash_object.rb', line 50 def initialize(sym, ) @sym = sym @required = [:required] != false @default = [:default] @type = [:type] @single = [:single] @builder = [:builder] @name = [:name] if @type raise ConfigurationError, "'#{sym}' requires a type: #{@type}" unless @type.is_a?(Class) if !@type.respond_to?(:parse) raise ConfigurationError, "'#{sym}' attribute requires type '#{@type.name}' to implement 'parse'" end end end |
Instance Attribute Details
#name ⇒ Symbol (readonly)
Returns sym The name that is to be parsed from the Hash, if it is not the symbol name.
38 39 40 |
# File 'lib/hash_object.rb', line 38 def name @name end |
#sym ⇒ Symbol (readonly)
Returns sym The name of the method.
36 37 38 |
# File 'lib/hash_object.rb', line 36 def sym @sym end |
Instance Method Details
#default_value ⇒ Object
An abstraction around the default value of the object, whether it is a reified object or a Proc that will generate the default value.
108 109 110 111 112 113 114 |
# File 'lib/hash_object.rb', line 108 def default_value if @default.is_a?(Proc) @default.call else @default end end |
#set(obj, value) ⇒ Object
Sets the value of the newly created element, either parsing the value, setting the default, or using the builder.
73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 |
# File 'lib/hash_object.rb', line 73 def set(obj, value) if @type if @single value = @type.parse(value) else value = value.map{|e| @type.parse(e)} end elsif @builder if @single value = @builder.call(value) else value = value.map{|e| @builder.call(e)} end end obj.send("#{@sym}=".to_sym, value) end |
#set_default(obj) ⇒ nil
Sets the default value of the object.
95 96 97 98 99 100 101 |
# File 'lib/hash_object.rb', line 95 def set_default(obj) if @required raise ConfigurationError, "The '#{@sym}' attribute is required for '#{obj.class.name}'" else obj.send("#{@sym}=".to_sym, default_value) end end |