Class: Namely::Collection

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

Instance Method Summary collapse

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

#allArray<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.

Returns:



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.

Parameters:

  • attributes (Hash)

    the attributes of the model being built.

Returns:



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.

Examples:

profiles_collection.create!(
  first_name: "Beardsly",
  last_name: "McDog",
  email: "[email protected]"
)

Parameters:

  • attributes (Hash)

    the attributes of the model being created.

Returns:

  • (Model)

    the created model.



41
42
43
# File 'lib/namely/collection.rb', line 41

def create!(attributes)
  build(attributes).save!
end

#endpointObject



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.

Parameters:

  • id (#to_s)

Returns:

  • (Boolean)


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.

Parameters:

  • id (#to_s)

Returns:

Raises:



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