class BrainstemAdaptor::Association

Attributes

collection_name[R]
foreign_key[R]
name[R]
record[R]
specification[R]

Public Class Methods

new(record, name) click to toggle source

@param record [BrainstemAdaptor::Record] @param name [String, Symbol]

# File lib/brainstem_adaptor/association.rb, line 9
def initialize(record, name)
  @name = name.to_s

  unless record.has_association?(@name)
    raise ArgumentError, "No '#@name' specification found for #{record.collection_name}"
  end

  @record          = record
  @specification   = record.associations_specification[@name]
  @collection_name = @specification['collection'] || @name
  @foreign_key     = @specification['foreign_key']
end

Public Instance Methods

==(other) click to toggle source

@param other [Enumerable] @return [true, false]

# File lib/brainstem_adaptor/association.rb, line 24
def ==(other)
  other == each.to_a
end
[](order) click to toggle source

@param order [Integer] Index in collection starting from zero

# File lib/brainstem_adaptor/association.rb, line 29
def [](order)
  records[order]
end
all()
Alias for: records
each(&block) click to toggle source

@return [Enumerable]

# File lib/brainstem_adaptor/association.rb, line 34
def each(&block)
  records.each(&block)
end
has_many?() click to toggle source
# File lib/brainstem_adaptor/association.rb, line 38
def has_many?
  ids.is_a?(Array)
end
has_one?() click to toggle source
# File lib/brainstem_adaptor/association.rb, line 42
def has_one?
  !has_many?
end
loaded?() click to toggle source

Checks if association has been included in request @return [true, false]

# File lib/brainstem_adaptor/association.rb, line 48
def loaded?
  (!record[foreign_key].nil?) && (!!record.response[@collection_name].try(:any?))
end
records() click to toggle source

@return [Array<BrainstemAdaptor::Record>]

# File lib/brainstem_adaptor/association.rb, line 53
def records
  [*ids].map do |id|
    BrainstemAdaptor::Record.new(collection_name, id, record.response)
  end
end
Also aliased as: all
reflect() click to toggle source

Returns relation object for has_many associations and record for has_one Acts as AR::find for has_one associations, as AR::where for has_many @return [BrainstemAdaptor::Record, self]

# File lib/brainstem_adaptor/association.rb, line 63
def reflect
  has_many? ? self : records.first
end

Private Instance Methods

ids() click to toggle source
# File lib/brainstem_adaptor/association.rb, line 69
def ids # TODO(SZ): move to public?
  record[foreign_key]
end