Class: Namely::Collection
- Inherits:
-
Object
- Object
- Namely::Collection
- Defined in:
- lib/namely/collection.rb
Instance Method Summary collapse
-
#all ⇒ Array<Model>
Return every instance of this model.
-
#build(attributes) ⇒ Model
Instantiate (but don’t save) a new Model with the given attributes.
-
#create!(attributes) ⇒ Model
Create a new Model on the server with the given attributes.
- #endpoint ⇒ Object
-
#exists?(id) ⇒ Boolean
Returns true if a Model with this ID exists, false otherwise.
-
#find(id) ⇒ Model
Fetch a model from the server by its ID.
-
#initialize(resource_gateway) ⇒ Collection
constructor
A new instance of Collection.
Constructor Details
#initialize(resource_gateway) ⇒ Collection
Returns a new instance of Collection.
5 6 7 |
# File 'lib/namely/collection.rb', line 5 def initialize(resource_gateway) @resource_gateway = resource_gateway end |
Instance Method Details
#all ⇒ Array<Model>
Return every instance of this model.
A model might have quite a few instances. If this is the case, the query may take some time (several seconds) and the resulting array may be very large.
16 17 18 |
# File 'lib/namely/collection.rb', line 16 def all resource_gateway.json_index.map { |model| build(model) } end |
#build(attributes) ⇒ Model
Instantiate (but don’t save) a new Model with the given attributes.
25 26 27 |
# File 'lib/namely/collection.rb', line 25 def build(attributes) Model.new(resource_gateway, attributes) end |
#create!(attributes) ⇒ Model
Create a new Model on the server with the given attributes.
41 42 43 |
# File 'lib/namely/collection.rb', line 41 def create!(attributes) build(attributes).save! end |
#endpoint ⇒ Object
45 46 47 |
# File 'lib/namely/collection.rb', line 45 def endpoint resource_gateway.endpoint end |
#exists?(id) ⇒ Boolean
Returns true if a Model with this ID exists, false otherwise.
54 55 56 57 58 59 |
# File 'lib/namely/collection.rb', line 54 def exists?(id) resource_gateway.show_head(id) true rescue RestClient::ResourceNotFound false end |
#find(id) ⇒ Model
Fetch a model from the server by its ID.
68 69 70 71 72 |
# File 'lib/namely/collection.rb', line 68 def find(id) build(resource_gateway.json_show(id)) rescue RestClient::ResourceNotFound raise NoSuchModelError, "Can't find any #{endpoint} with id \"#{id}\"" end |