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

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.



68
69
70
71
72
73
74
75
76
# File 'lib/activeresource/lib/active_resource/collection.rb', line 68

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.



97
98
99
# File 'lib/activeresource/lib/active_resource/collection.rb', line 97

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

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.



116
117
118
119
# File 'lib/activeresource/lib/active_resource/collection.rb', line 116

def call
  request_resources!
  self
end

#each(&block) ⇒ Object



189
190
191
# File 'lib/activeresource/lib/active_resource/collection.rb', line 189

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"


144
145
146
147
148
# File 'lib/activeresource/lib/active_resource/collection.rb', line 144

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"


164
165
166
167
168
# File 'lib/activeresource/lib/active_resource/collection.rb', line 164

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.



88
89
90
# File 'lib/activeresource/lib/active_resource/collection.rb', line 88

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

#refreshObject

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

Returns

Array<Object>

The collection of resources retrieved from the API.



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

def refresh
  @requested = false
  request_resources!
end

#requested?Boolean

Checks if the collection has been requested.

Returns

Boolean

true if the collection has been requested, false otherwise.

Returns:

  • (Boolean)


126
127
128
# File 'lib/activeresource/lib/active_resource/collection.rb', line 126

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)


183
184
185
186
187
# File 'lib/activeresource/lib/active_resource/collection.rb', line 183

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