class Findable::Collection

Record collection class

Attributes

model[R]
records[R]
to_a[R]

Public Class Methods

new(model, records) click to toggle source
# File lib/findable/collection.rb, line 8
def initialize(model, records)
  raise ArgumentError unless records.is_a?(Array)
  @model = model
  @records = records
end

Public Instance Methods

each() { |record| ... } click to toggle source
# File lib/findable/collection.rb, line 25
def each
  if block_given?
    records.each {|record| yield(record) }
  else
    records.to_enum
  end
end
find(ids) click to toggle source
# File lib/findable/collection.rb, line 33
def find(ids)
  if ids.is_a?(Array)
    if refined = records.select {|record| record.id.in?(ids) }
      regenerate(refined)
    else
      raise not_found(id: ids)
    end
  else
    records.detect {|record| record.id == ids } || (raise not_found(id: ids))
  end
end
find_by(conditions) click to toggle source
# File lib/findable/collection.rb, line 45
def find_by(conditions)
  records.detect {|record|
    conditions.all? {|k, v| record.public_send(k) == v }
  }
end
find_by!(conditions) click to toggle source
# File lib/findable/collection.rb, line 51
def find_by!(conditions)
  find_by(conditions.dup) || (raise not_found(conditions))
end
inspect() click to toggle source
# File lib/findable/collection.rb, line 86
def inspect
  "[#{records.map(&:inspect).join(",\n")}]"
end
order(*columns) click to toggle source
# File lib/findable/collection.rb, line 61
def order(*columns)
  columns.flatten!
  raise ArgumentError, "Must contain arguments" if columns.empty?

  regenerate(records.sort_by {|record|
    columns.map {|column| record.public_send(column) }
  })
end
ordered_find(*_ids) click to toggle source
# File lib/findable/collection.rb, line 70
def ordered_find(*_ids)
  _ids.flatten!
  records.index_by(&:id).values_at(*_ids)
end
pluck(*columns) click to toggle source
# File lib/findable/collection.rb, line 75
def pluck(*columns)
  columns.flatten!
  return records.map {|record| record.attributes.values } if columns.empty?
  single = (columns.size == 1)

  records.map {|record|
    values = columns.map {|column| record.public_send(column) }
    single ? values.first : values
  }
end
presence() click to toggle source
# File lib/findable/collection.rb, line 21
def presence
  present? ? self : nil
end
where(conditions) click to toggle source
# File lib/findable/collection.rb, line 55
def where(conditions)
  regenerate(records.select {|record|
    conditions.all? {|k, v| record.public_send(k) == v }
  })
end

Private Instance Methods

not_found(params) click to toggle source
# File lib/findable/collection.rb, line 95
def not_found(params)
  RecordNotFound.new(model, params)
end
regenerate(records) click to toggle source
# File lib/findable/collection.rb, line 91
def regenerate(records)
  self.class.new(model, records)
end