开发者

How to run a standard chunk of code from inside a controller/model?

I have a 'chunk of code' that performs calculations on data and updates some tables based on those calculations.

I'd like t开发者_JAVA百科o be able to reference that chunk of code from multiple locations, something like this:

# from controller or model
def ...
  ...
  run `chunk of code`
  ...
end

This is an inordinately simple question - where would chunk of code go and how would I get Rails to run it from controller/model?


Calculations or table updates belongs to a model, so what about defining some new class method in your model, e.g.

def self.calculate
  ...
  chunk of code
  ...
end

it can be then called from both model and controller


I managed it by doing:

def calculate
   chunk of code
end

Then to call it from the model/controller:

def some_other_action
  ...
  @record.calculate (or self.calculate in model)
  ...
end
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜