Class: FindAI::BaseModel

Inherits:
Object
  • Object
show all
Defined in:
lib/find-ai/base_model.rb

Instance Method Summary collapse

Constructor Details

#initialize(data = {}) ⇒ BaseModel

Create a new instance of a model.

Parameters:

  • data (Hash) (defaults to: {})

    Model attributes.



144
145
146
147
148
149
150
151
152
153
154
155
156
# File 'lib/find-ai/base_model.rb', line 144

def initialize(data = {})
  @data = {}
  # TODO: what if data isn't a hash?
  data.each do |field_name, value|
    next if value.nil?

    field = self.class.fields[field_name.to_sym]
    if field
      next if field[:mode] == :w
    end
    @data[field_name.to_sym] = value
  end
end

Instance Method Details

#[](key) ⇒ Object

Lookup attribute value by key in the object. If this key was not provided when the object was formed (e.g. because the API response did not include that key), returns nil. It is valid to lookup keys that are not in the API spec, for example to access undocumented features. Lookup by anything other than a Symbol is an ArgumentError.

Parameters:

  • key (Symbol)

    Key to look up by.

Returns:

  • (Object)

    Parsed / typed value at the given key, or nil if no data is available.



183
184
185
186
187
188
# File 'lib/find-ai/base_model.rb', line 183

def [](key)
  if !key.instance_of?(Symbol)
    raise ArgumentError, "Expected symbol key for lookup, got #{key.inspect}"
  end
  @data[key]
end

#inspectString

Returns:

  • (String)


191
192
193
# File 'lib/find-ai/base_model.rb', line 191

def inspect
  "#<#{self.class.name}:0x#{object_id.to_s(16)} #{@data.inspect}>"
end

#to_hHash{Symbol => Object} Also known as: to_hash

Returns a Hash of the data underlying this object. Keys are Symbols and values are the parsed / typed domain objects. The return value indicates which values were ever set on the object - i.e. there will be a key in this hash if they ever were, even if the set value was nil. This method is not recursive. The returned value is shared by the object, so it should not be mutated.

Returns:

  • (Hash{Symbol => Object})

    Data for this object.



167
168
169
# File 'lib/find-ai/base_model.rb', line 167

def to_h
  @data
end

#to_sString

Returns:

  • (String)


196
197
198
# File 'lib/find-ai/base_model.rb', line 196

def to_s
  @data.to_s
end