Class: Remotely::Collection

Inherits:
Array
  • Object
show all
Defined in:
lib/remotely/collection.rb

Instance Method Summary collapse

Constructor Details

#initialize(parent, klass, *args, &block) ⇒ Collection

Returns a new instance of Collection.



3
4
5
6
7
# File 'lib/remotely/collection.rb', line 3

def initialize(parent, klass, *args, &block)
  @parent = parent
  @klass  = klass
  super(*args, &block)
end

Instance Method Details

#allRemotely::Collection

Mimic an ActiveRecord::Relation, but just return self since that’s already an array.

Returns:



34
35
36
# File 'lib/remotely/collection.rb', line 34

def all
  self
end

#build(attrs = {}) ⇒ Remotely::Model

Instantiate a new model object, pre-build with a foreign key attribute set to it’s parent, and add it to itself.

NOTE: Does not persist the new object. You must call save on the new object to persist it. To instantiate and persist in one operation

Parameters:

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

    Attributes to instantiate the new object with.

Returns:

See Also:



59
60
61
62
63
64
65
# File 'lib/remotely/collection.rb', line 59

def build(attrs={})
  attribute  = "#{@parent.class.model_name.element.to_sym}_id".to_sym
  value      = @parent.id
  attrs.merge!(attribute => value)

  @klass.new(attrs).tap { |m| self << m }
end

#create(attrs = {}) ⇒ Object

Same as #build, but saves the new model object as well.

See Also:



71
72
73
# File 'lib/remotely/collection.rb', line 71

def create(attrs={})
  build(attrs).tap { |m| m.save }
end

#find(id) ⇒ Remotely::Model

Returns the first Model object with id.

Parameters:

  • id (Fixnum)

    id of the record

Returns:



14
15
16
# File 'lib/remotely/collection.rb', line 14

def find(id)
  select { |e| e.id.to_i == id.to_i }.first
end

#order(attribute) ⇒ Object

Order the result set by a specific attribute.

Examples:

Sort by name

Thing.where(:type => "awesome").order(:name)


45
46
47
# File 'lib/remotely/collection.rb', line 45

def order(attribute)
  Collection.new(@parent, @klass, sort_by(&attribute))
end

#where(attrs = {}, &block) ⇒ Remotely::Collection

Returns a new Collection object consisting of all the Model objects matching ‘attrs`.

Parameters:

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

    Search criteria in key-value form

Returns:



24
25
26
27
# File 'lib/remotely/collection.rb', line 24

def where(attrs={}, &block)
  block = lambda { |e| attrs.all? { |k,v| e.send(k) == v }} unless block_given?
  Collection.new(@parent, @klass, select(&block))
end