我在我的模型中有一个非常大的函数,我想把它存储在其他地方,以保持我的模型干燥。我读到在ApplicationHelper中存储方法,然后从模型中调用它们是一个坏主意。那么什么是一个好主意呢?我希望我的大方法有一个单独的文件,并从模型中调用它们。
发布于 2013-01-12 06:58:50
使用关注点。https://gist.github.com/1014971
这很简单。在app/models/concerns
中创建文件your_functionality.rb
,如下所示:
module YourFunctionality
extend ActiveSupport::Concern
def your_fat_method
# insert...
end
end
在你的模型中,简单地:
include YourFunctionality
发布于 2013-01-12 06:20:09
你可以创建一个“普通的旧ruby对象(PORO)”来为你做你的工作。假设您有一个计算用户逾期金额的方法。
因此,您可以创建app/services/calculates_overages.rb
class CalculatesOverages
def initialize(user)
@user = user
end
def calculate
# your method goes here
end
end
然后,您可以:
class User < ActiveRecord::Base
def overage_amount
CaluclatesOverage.new(self).calculate
end
end
或者,在控制器中,您可以:
def show
@amount = CaluclatesOverage.new(current_user).calculate
end
app/services目录也可以是app/model或lib目录。这方面(目前)还没有固定的约定。
https://stackoverflow.com/questions/14287553
复制相似问题