Question

I'm writing a library to consume an API using Active Resource (4.0.0). The API returns nested resources as a URL, rather than an array of objects.

For instance, when I load a Parent object (an ActiveResource::Base descendant) using Parent.find(1), I get a JSON response similar to:

"parent": {
  "username": "alex",
  "children": "http://domain.com/parents/alex/children"
}

Assuming I have another ActiveResource::Base subclass called Children, how can I access the children of this Parent object, as an array of Children instances created by requesting the provided children url? I'll get you started:

class Parent < ActiveResource::Base
  def children
    # HALP
    # (super returns the children url as a string)
  end
end
Was it helpful?

Solution

You can specify a :from parameter to #find:

class Parent < ActiveResource::Base
  # ...

  def children
    Child.find(:all, from: URI(super).path)
  end
end

However: it only allows you to change the path, not the complete URL. If the host part of the resource's URL might change, you have to change the resource's site also.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top