简体   繁体   中英

Extending ActiveResource Class

Is it possible to extend an ActiveResource class unmarshalled from a response?

Example of ActiveResource request:

GET http://www.exampleservice.com/products.json

Response

[{name:'Product X', price:14.5, features:[{name:'Soft'}, {name:'Green'}, {name:'Heavy'}]}]

This response would be unmarshalled to a Product object with an array of Product::Feature objects. Is it possible to add some custom method/attributes to this Product::Feature class?

To answer my own question:

I created a new module including my methods and extended each unmarshalled object of Product::Feature with it. This looks like the following:

module FeatureExtension
  def my_method
    # do something
  end
end

Somewhere after I received a Product from ActiveResource I used the code:

@product.features.each do |feature|
  feature.extend(FeatureExtension)
  feature.my_method # Now it is possible to call the method
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM