Skip to content

4. Custom ActiveCachedResource::Collection

Jean Luis Urena edited this page Apr 23, 2025 · 2 revisions

Summary

ActiveCachedResource::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 ActiveCachedResource::Collection to handle parsing index responses.

Usage

  1. Inherit from ActiveCachedResource::Collection.
  2. Override the #parse_response method.
  3. [Optional] To have instance methods persisted into cache, and later on retrieved use ActiveResource::Collection.persisted_attribute.
# GET /posts.json delivers following response body:
#   {
#     instances: [
#       {
#         title: "ActiveResource now has associations",
#         body: "Lorem Ipsum"
#       },
#       {...}
#     ],
#     next_page: "/posts.json?page=2",
#     count: 100
#   }

class Post < ActiveCachedResource::Collection
  persisted_attribute :count, :next_page

  def parse_response(parsed)
    @elements = parsed[:instances]
    @count = parsed[:count]
    @next_page = parsed[:next_page]
  end
end

Clone this wiki locally