[英]Extending ActiveResource Class
Is it possible to extend an ActiveResource class unmarshalled from a response? 是否可以扩展从响应中未编组的ActiveResource类?
Example of ActiveResource request: ActiveResource请求的示例:
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. 该响应将是解组的Product
具有的阵列对象Product::Feature
对象。 Is it possible to add some custom method/attributes to this Product::Feature
class? 是否可以向此Product::Feature
类添加一些自定义方法/属性?
To answer my own question: 要回答我自己的问题:
I created a new module including my methods and extended each unmarshalled object of Product::Feature
with it. 我创建了一个包含我的方法的新模块,并使用它扩展了Product::Feature
每个未编组对象。 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: 从ActiveResource
收到Product
,我使用了以下代码:
@product.features.each do |feature|
feature.extend(FeatureExtension)
feature.my_method # Now it is possible to call the method
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.