在哪里为控制器添加辅助方法?

时间:2012-08-14 10:41:23

标签: ruby-on-rails ruby-on-rails-3

我希望编写某些方法来处理字符串,以及在我的许多控制器中发生的其他任务。我知道在您的控制器中包含帮助程序的不良做法,所以我只是想知道,在控制器中使用应用程序范围的方法的最佳位置在哪里?

我意识到有些人会说将它们放入模型中,但你必须意识到并非所有的控制器都有相关的模型。任何和所有输入将不胜感激。

6 个答案:

答案 0 :(得分:11)

我倾向于把它们变成帮助者。它们包含在视图中的事实 自动对我来说不是问题。你也可以把它们放进去 像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

答案 1 :(得分: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

答案 2 :(得分:6)

我建议将它们放在lib文件夹中。例如,我有:

lib/utils/string_utils

module StringUtils

  def foo
     ...
  end
end

class BarController < ActionController::Base
  include StringUtils
end

这展示了一种称为 Fat模型,精简控制器的良好方法,在这种情况下,我们使用Mixins而不是模型来分离逻辑,但想法是相同的。您希望控制器尽可能简单。

答案 3 :(得分:3)

这完全取决于您的需求。我将在这里提供2个例子。它们都只是一个自定义库,位于lib目录下。

第一个示例 - “自定义字符串处理”

# lib/filters.rb
module Filters

  # Converts value to canonical view
  def self.phone(value)
    # remove all non-digits
    clean_value = value.gsub(/\D/, '')

    country_codes = configus.phone.country_codes
    area_code = configus.phone.defaults.area_code

    case clean_value.length
      when 7
        "#{area_code}#{clean_value}"
      when 11
        # remove country code only if phone starts with the allowed country code
        if country_codes.include?(clean_value[0].to_i)
          clean_value[1..-1]
        else
          clean_value
        end
      else clean_value
    end
  end

# usage
# app/api/phones_controller.rb
class Api::PhonesController < Api::ApplicationController

  def exists
    if params[:q]
      clean_value = Filters.phone(params[:q])
      ...
    end
  end
end

第二个示例 - Flash消息的助手

# lib/flash_helper.rb
module FlashHelper
  def flash_translate(key, options = {})
    scope = [:flash, :controllers]
    scope += params[:controller].split('/')
    scope << params[:action]

    t(key, {:scope => scope}.merge(options))
  end
end

# app/application_controller.rb
class ApplicationController < ActionController::Base
  include FlashHelper
end

# usage
# app/your_controller.rb
class YourController < ApplicationController

  def create
    @object = Object.new(params[:object])

    if @object.save
      flash[:success] = flash_translate(:success)
      ...
    end
  end
end

注意:不要忘记将lib目录添加到自动加载路径。在config/application.rb添加/修改此行config.autoload_paths += %W(#{config.root}/lib)。 所以对我来说答案是lib目录。

答案 4 :(得分:1)

从Rails 4开始,它有一个专用文件夹app/controllers/concerns。因此,您可以在那里创建一个模块,然后将其包含在特定的控制器或ApplicationController中(如果您需要它在所有控制器中都可用)。

答案 5 :(得分:0)

如果在许多控制器中使用这些方法,我会在application_controller.rb中定义它们。每个控制器都将继承它,并且能够使用那里定义的任何方法

相关问题