Method: ActiveResource::Collection#initialize
- Defined in:
- lib/active_resource/collection.rb
#initialize(elements = []) ⇒ 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 inherets 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 initialize(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 initialize method will receive the ActiveResource::Formats parsed result and should set @elements.
59 60 61 |
# File 'lib/active_resource/collection.rb', line 59 def initialize(elements = []) @elements = elements end |