fly*_*llo 19 ruby-on-rails ruby-on-rails-3
我期待编写某些方法来处理字符串,以及在我的许多控制器中发生的其他任务.我知道在你的控制器中加入帮助器是不好的做法,所以我只是想知道,在控制器中使用应用程序范围的方法的最佳位置在哪里?
我意识到有些人会说将它们放入模型中,但你必须意识到并非所有的控制器都有相关的模型.任何和所有输入将不胜感激.
Sim*_*tsa 12
我倾向于把它们变成帮手.事实上,它们自动包含在视图中对我来说不是问题.您也可以将它们放入app/concerns/lib /类似的东西中
我不喜欢使用私有方法来混淆ApplicationController,因为这经常变得一团糟.
例:
module AuthenticationHelper
def current_user
@current_user # ||= ...
end
def authenticate!
redirect_to new_session_url unless current_user.signed_in?
end
end
module MobileSubdomain
def self.included(controller)
controller.before_filter :set_mobile_format
end
def set_mobile_format
request.format = :mobile if request.subdomain == "m"
end
end
class ApplicationController
include AuthenticationHelper
include MobileSubdomain
end
Run Code Online (Sandbox Code Playgroud)
San*_*ing 10
如果您需要在应用程序范围中使用方法,那么我建议您将这些方法保留在应用程序控制器中,以便在视图中使用它们.将它们声明为辅助方法.
例如,
class ApplicationController < ActionController::Base
helper_method :current_user, :some_method
def current_user
@user ||= User.find_by_id(session[:user_id])
end
def some_method
end
end
Run Code Online (Sandbox Code Playgroud)
我建议将它们放在lib文件夹中.所以我举例说:
lib/utils/string_utils
module StringUtils
def foo
...
end
end
class BarController < ActionController::Base
include StringUtils
end
Run Code Online (Sandbox Code Playgroud)
这展示了称为Fat模型,Thin控制器的良好方法,在这种情况下,我们使用Mixins而不是模型来分离逻辑,但想法是相同的.您希望控制器尽可能简单.
| 归档时间: |
|
| 查看次数: |
10298 次 |
| 最近记录: |