class BrainstemAdaptor::Record

Attributes

collection_name[R]
id[R]
response[R]

Public Class Methods

new(collection_name, id, response = nil) click to toggle source

@param collection_name [String, Symbol] @param id @param response [BrainstemAdaptor::Response, nil]

Calls superclass method
# File lib/brainstem_adaptor/record.rb, line 8
def initialize(collection_name, id, response = nil)
  super([])
  @collection_name = collection_name.to_s
  @id = id
  load_fields_with(response) if response
end

Public Instance Methods

[](key) click to toggle source

@param key [String]

Calls superclass method
# File lib/brainstem_adaptor/record.rb, line 16
def [](key)
  if has_key?(key = key.to_s)
    super
  elsif has_association?(key)
    association_by_name(key).reflect
  end
end
association_by_name(name) click to toggle source

@param name [String] @raise [ArgumentError] if name is not related to any association @return [BrainstemAdaptor::Association]

# File lib/brainstem_adaptor/record.rb, line 32
def association_by_name(name)
  if has_association?(name)
    (@associations ||= {})[name] ||= BrainstemAdaptor::Association.new(self, name)
  end
end
associations_specification() click to toggle source

@return [Hash]

# File lib/brainstem_adaptor/record.rb, line 25
def associations_specification
  @associations_specification ||= specification['associations'] || {}
end
has_association?(name) click to toggle source

@param name [String]

# File lib/brainstem_adaptor/record.rb, line 39
def has_association?(name)
  associations_specification.has_key?(name.to_s)
end
specification() click to toggle source

@return [Hash]

# File lib/brainstem_adaptor/record.rb, line 44
def specification
  @specification ||= {}
end

Protected Instance Methods

load_fields_with(response, fields_to_reload = []) click to toggle source

@param response [Brainstem::Response] @param fields_to_reload [Array] Reloads all fields if empty

# File lib/brainstem_adaptor/record.rb, line 52
def load_fields_with(response, fields_to_reload = [])
  @response = response

  if @response.specification.has_key?(collection_name)
    @specification = @response.specification[collection_name] || {}
  else
    raise BrainstemAdaptor::InvalidResponseError, "Can't find '#{collection_name}' association in specification"
  end

  collection = @response[@collection_name] or
    raise BrainstemAdaptor::InvalidResponseError, "No such collection #@collection_name"

  fields = collection[@id] or
    raise BrainstemAdaptor::InvalidResponseError, "No such record #{@collection_name}##{@id}"

  if fields_to_reload.any?
    merge!(fields.slice(*fields_to_reload))
  else
    merge!(fields)
  end
end