Class: Structure
- Inherits:
-
Object
- Object
- Structure
- Defined in:
- lib/structure.rb,
lib/structure/json.rb,
lib/structure/version.rb
Overview
Structure is a typed key/value container
Defined Under Namespace
Modules: JSON Classes: Definition, Wrapper
Constant Summary collapse
- VERSION =
'0.22.0'
Class Method Summary collapse
-
.blueprint ⇒ Hash
A collection of keys and their definitions.
-
.key(name, type = String, default = nil) ⇒ Object
Defines a key.
Instance Method Summary collapse
-
#==(other) ⇒ true, false
Compares this object with another object for equality.
-
#initialize(hsh = {}) ⇒ Structure
constructor
Builds a new structure.
-
#to_hash ⇒ Hash
A hash representation of the structure.
Constructor Details
#initialize(hsh = {}) ⇒ Structure
Builds a new structure
150 151 152 153 154 155 156 157 |
# File 'lib/structure.rb', line 150 def initialize(hsh = {}) @attributes = blueprint.inject({}) do |a, (k, v)| a[k] = v.default.dup rescue v.default a end hsh.each { |k, v| self.send("#{k}=", v) } end |
Class Method Details
.blueprint ⇒ Hash
Returns a collection of keys and their definitions.
103 104 105 |
# File 'lib/structure.rb', line 103 def blueprint @blueprint ||= {} end |
.key(name, type = String, default = nil) ⇒ Object
Note:
Key type defaults to String
if not specified.
Defines a key
115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 |
# File 'lib/structure.rb', line 115 def key(name, type = String, default = nil) name = name.to_sym if method_defined?(name) raise NameError, "#{name} is taken" end if default && !default.is_a?(type) raise TypeError, "#{default} isn't a #{type}" end # Add key to blueprint. blueprint[name] = Definition.new(type, default) # Define getter. define_method(name) do @attributes[name] end # Define setter. define_method("#{name}=") do |val| @attributes[name] = self.class.blueprint[name].typecast(val) end end |
Instance Method Details
#==(other) ⇒ true, false
Compares this object with another object for equality
A structure is equal to another object when both are of the same class and their attributes are the same.
181 182 183 |
# File 'lib/structure.rb', line 181 def ==(other) other.is_a?(self.class) && attributes == other.attributes end |
#to_hash ⇒ Hash
Returns a hash representation of the structure.
160 161 162 163 164 165 166 167 168 169 170 171 172 |
# File 'lib/structure.rb', line 160 def to_hash @attributes.inject({}) do |a, (k, v)| a[k] = if v.respond_to?(:to_hash) v.to_hash elsif v.is_a?(Array) v.map { |e| e.respond_to?(:to_hash) ? e.to_hash : e } else v end a end end |