Class: Remotely::Collection
- Inherits:
-
Array
- Object
- Array
- Remotely::Collection
- Defined in:
- lib/remotely/collection.rb
Instance Method Summary collapse
-
#all ⇒ Remotely::Collection
Mimic an ActiveRecord::Relation, but just return self since that’s already an array.
-
#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.
-
#create(attrs = {}) ⇒ Object
Same as #build, but saves the new model object as well.
-
#find(id) ⇒ Remotely::Model
Returns the first Model object with
id
. -
#initialize(parent, klass, *args, &block) ⇒ Collection
constructor
A new instance of Collection.
-
#order(attribute) ⇒ Object
Order the result set by a specific attribute.
-
#where(attrs = {}, &block) ⇒ Remotely::Collection
Returns a new Collection object consisting of all the Model objects matching ‘attrs`.
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
#all ⇒ Remotely::Collection
Mimic an ActiveRecord::Relation, but just return self since that’s already an array.
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
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.
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
.
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.
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`.
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 |