Module: IOSTSdk::Models::InstanceMethods

Defined in:
lib/iost_sdk/models.rb

Instance Method Summary collapse

Instance Method Details

#populate(model_data:) ⇒ Object

Creates an instance of a model from the JSON string.

Parameters:

  • model_data (Hash)

    the JSON string of the model data

Returns:

  • an instance of model_class if model_data is valid.



192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
# File 'lib/iost_sdk/models.rb', line 192

def populate(model_data:)
  # if nil, short-curcuit
  return nil unless model_data

  # the model class is expected implement "attr_names" method
  model_attr_names = self.class.attr_names || []
  # proceed ONLY if actual data has a subset of keys of what's defined by the class
  unless Set.new(model_data.keys).subset?(Set.new(model_attr_names))
    raise IOSTSdk::Errors::InvalidModelDataError.new(
      self.class.name,
      model_attr_names,
      model_data.keys
    )
  end
  # create the model
  model_attr_names.each do |k|
    v = model_data[k]
    # set the instance var
    instance_variable_set("@#{k}", parse(data_key: k, data_value: v))
    # define the attr_reader
    self.class.send(:define_method, k.to_sym) do
      instance_variable_get("@#{k}")
    end
  end

  self
end