質問

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
役に立ちましたか?

解決

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.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top