module IOSTSdk::Models::InstanceMethods

Public Instance Methods

populate(model_data:) click to toggle source

Creates an instance of a model from the JSON string.

@param model_data [Hash] the JSON string of the model data @return an instance of model_class if model_data is valid.

# 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