Module: JsonObject::ClassMethods
- Defined in:
- lib/json_object.rb
Overview
This will be extended when JsonObject is included in a class.
Instance Method Summary collapse
-
#create(hash, parent = nil) ⇒ Object
Provides a default implementation of this method, which is a required call, used by #object_accessor.
-
#object_accessor(attribute, opts = {}) ⇒ Object
Similar to value_accessor.
-
#value_accessor(attribute, opts = {}) ⇒ Object
Creates an accessor method to retrieve values from the stored #json_hash.
-
#value_accessors(*args) ⇒ Object
Convienience method for defining muiltiple accessors with one call.
Instance Method Details
#create(hash, parent = nil) ⇒ Object
Provides a default implementation of this method, which is a required call, used by #object_accessor
Usable with a class that can be initialized with no arguments e.g. new()
114 115 116 117 118 119 |
# File 'lib/json_object.rb', line 114 def create hash, parent=nil new().tap do |obj| obj.parent = parent obj.json_hash = hash end end |
#object_accessor(attribute, opts = {}) ⇒ Object
Similar to value_accessor.
179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'lib/json_object.rb', line 179 def object_accessor attribute, opts={} klass = opts.fetch(:class, JsonObject.default_json_object_class) set_parent = opts.fetch(:set_parent, true) create_value_accessor_method attribute, opts do |obj| value_for_attribute = obj.json_hash[attribute.to_s] methods_value = if value_for_attribute.is_a? Array value_for_attribute.inject([]) do |classes, hash| classes << klass.create(hash, set_parent ? obj : nil) end else value_for_attribute.nil? ? nil : klass.create(value_for_attribute, set_parent ? obj : nil) end end self end |
#value_accessor(attribute, opts = {}) ⇒ Object
Creates an accessor method to retrieve values from the stored JsonObject#json_hash
141 142 143 144 145 146 147 148 149 150 |
# File 'lib/json_object.rb', line 141 def value_accessor attribute, opts={} default_value = opts[:default] proc_provided = opts[:proc] create_value_accessor_method attribute, opts do |obj| value = obj.json_hash[attribute.to_s] value = default_value if value.nil? proc_provided ? proc_provided.call(obj, value) : value end self end |
#value_accessors(*args) ⇒ Object
Convienience method for defining muiltiple accessors with one call.
161 162 163 164 165 166 |
# File 'lib/json_object.rb', line 161 def value_accessors *args args.each do |values| value_accessor *Array(values) end self end |