Class: ActiveResource::Collection

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/activeresource/lib/active_resource/collection.rb

Overview

:nodoc:

Direct Known Subclasses

ActiveCachedResource::Collection

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(elements = [], from = nil) ⇒ Collection

ActiveResource::Collection is a wrapper to handle parsing index responses that do not directly map to Rails conventions.

You can define a custom class that inherits from ActiveResource::Collection in order to to set the elements instance.

GET /posts.json delivers following response body:

{
  posts: [
    {
      title: "ActiveResource now has associations",
      body: "Lorem Ipsum"
    },
    {...}
  ],
  next_page: "/posts.json?page=2"
}

A Post class can be setup to handle it with:

class Post < ActiveResource::Base
  self.site = "http://example.com"
  self.collection_parser = PostCollection
end

And the collection parser:

class PostCollection < ActiveResource::Collection
  attr_accessor :next_page
  def parse_response(parsed = {})
    @elements = parsed['posts']
    @next_page = parsed['next_page']
  end
end

The result from a find method that returns multiple entries will now be a PostParser instance. ActiveResource::Collection includes Enumerable and instances can be iterated over just like an array.

@posts = Post.find(:all) # => PostCollection:xxx
@posts.next_page         # => "/posts.json?page=2"
@posts.map(&:id)         # =>[1, 3, 5 ...]

The ActiveResource::Collection#parse_response method will receive the ActiveResource::Formats parsed result and should set @elements.



85
86
87
88
89
90
91
92
93
# File 'lib/activeresource/lib/active_resource/collection.rb', line 85

def initialize(elements = [], from = nil)
  @from = from
  @elements = elements
  @requested = false
  @query_params = {}
  @path_params = {}
  # This can get called without a response, so parse only if response is present
  parse_response(@elements) if @elements.present?
end

Instance Attribute Details

#fromObject (readonly)

Returns the value of attribute from.



22
23
24
# File 'lib/activeresource/lib/active_resource/collection.rb', line 22

def from
  @from
end

#path_paramsObject

Returns the value of attribute path_params.



20
21
22
# File 'lib/activeresource/lib/active_resource/collection.rb', line 20

def path_params
  @path_params
end

#prefix_optionsObject

Returns the prefix options for the collection, which are used for constructing the resource path.

Returns

Hash

The prefix options for the collection.



114
115
116
# File 'lib/activeresource/lib/active_resource/collection.rb', line 114

def prefix_options
  @prefix_options || {}
end

#query_paramsObject

Returns the value of attribute query_params.



20
21
22
# File 'lib/activeresource/lib/active_resource/collection.rb', line 20

def query_params
  @query_params
end

#resource_classObject

Returns the value of attribute resource_class.



20
21
22
# File 'lib/activeresource/lib/active_resource/collection.rb', line 20

def resource_class
  @resource_class
end

Class Method Details

.noneActiveResource::Collection

Returns a frozen empty collection.

Returns:



27
28
29
30
31
# File 'lib/activeresource/lib/active_resource/collection.rb', line 27

def self.none
  new([]).tap do |collection|
    collection.instance_variable_set(:@requested, true)
  end
end

Instance Method Details

#callObject

Executes the request to fetch the collection of resources from the API and returns the collection.

Returns

ActiveResource::Collection

The collection of resources.



133
134
135
136
# File 'lib/activeresource/lib/active_resource/collection.rb', line 133

def call
  request_resources!
  self
end

#each(&block) ⇒ Object



207
208
209
# File 'lib/activeresource/lib/active_resource/collection.rb', line 207

def each(&block)
  request_resources!.each(&block)
end

#first_or_create(attributes = {}) ⇒ Object

Returns the first resource in the collection, or creates a new resource using the provided attributes if the collection is empty.

Arguments

attributes (Hash) - The attributes for creating the resource.

Returns

Object

The first resource, or a newly created resource if none exist.

Example

post = PostCollection.where(title: "New Post").first_or_create
# => Post instance with title "New Post"


161
162
163
164
165
# File 'lib/activeresource/lib/active_resource/collection.rb', line 161

def first_or_create(attributes = {})
  first || resource_class.create(query_params.update(attributes))
rescue NoMethodError
  raise "Cannot create resource from resource type: #{resource_class.inspect}"
end

#first_or_initialize(attributes = {}) ⇒ Object

Returns the first resource in the collection, or initializes a new resource using the provided attributes if the collection is empty.

Arguments

attributes (Hash) - The attributes for initializing the resource.

Returns

Object

The first resource, or a newly initialized resource if none exist.

Example

post = PostCollection.where(title: "New Post").first_or_initialize
# => Post instance with title "New Post"


181
182
183
184
185
# File 'lib/activeresource/lib/active_resource/collection.rb', line 181

def first_or_initialize(attributes = {})
  first || resource_class.new(query_params.update(attributes))
rescue NoMethodError
  raise "Cannot build resource from resource type: #{resource_class.inspect}"
end

#parse_response(elements) ⇒ Object

Processes and sets the collection elements. This method assigns the provided ‘elements` (or an empty array if none provided) to the `@elements` instance variable.

Arguments

elements (Array<Object>) - An optional array of resources to be set as the collection elements.

Defaults to an empty array.

This method is called after fetching the resource and can be overridden by subclasses to handle any specific response format of the API.



105
106
107
# File 'lib/activeresource/lib/active_resource/collection.rb', line 105

def parse_response(elements)
  @elements = elements || []
end

#reloadObject

Reload the collection by re-fetching the resources from the API.

Returns

Array<Object>

The collection of resources retrieved from the API.



123
124
125
126
# File 'lib/activeresource/lib/active_resource/collection.rb', line 123

def reload
  @requested = false
  call
end

#requested?Boolean

Checks if the collection has been requested.

Returns

Boolean

true if the collection has been requested, false otherwise.

Returns:

  • (Boolean)


143
144
145
# File 'lib/activeresource/lib/active_resource/collection.rb', line 143

def requested?
  @requested
end

#where(clauses = {}) ⇒ Object

Filters the collection based on the provided clauses (query parameters).

Arguments

clauses (Hash) - A hash of query parameters used to filter the collection.

Returns

ActiveResource::Collection

A new collection filtered by the specified clauses.

Example

filtered_posts = PostCollection.where(title: "Post 1")
# => PostCollection:xxx (filtered collection)

Raises:

  • (ArgumentError)


200
201
202
203
204
205
# File 'lib/activeresource/lib/active_resource/collection.rb', line 200

def where(clauses = {})
  raise ArgumentError, "expected a clauses Hash, got #{clauses.inspect}" unless clauses.is_a? Hash
  return self.class.none if resource_class.nil?
  new_clauses = query_params.merge(clauses)
  resource_class.where(new_clauses)
end