开发者

Augmenting a Rails Model with virtual attributes on runtime

开发者 https://www.devze.com 2023-01-30 09:18 出处:网络
I have a Rails Model with attributes X,Y,Z I want to dynamically add attributes P,Q to this model during the data fetch. The attributes P,Q do not need any persistence and is only for front-end manip

I have a Rails Model with attributes X,Y,Z

I want to dynamically add attributes P,Q to this model during the data fetch. The attributes P,Q do not need any persistence and is only for front-end manipulation.

Is this possible at all? I could achieve this by storing P,Q in another object and manipulating that along with the original model but thought of asking here wh开发者_运维技巧at could be best way.

[rails 2.3.5, ruby 1.8,7]


Try something like this in your model

def p
  @p || @p = fetch_p
end

This will allow you to call your_model.p. On the first call, it will call the fetch_p function and store it as a class attribute. On any subsequent call, it will simply returned the cached value.

0

精彩评论

暂无评论...
验证码 换一张
取 消