在 Rails 中,把对控制器和模型有用的函数放在哪里

在 Rails 中,把对控制器和模型有用的函数放在哪里

问题描述:

假设我有一个函数 trim_string(string),我想在整个 Rails 应用程序中使用它,在模型和控制器中.如果我把它放在应用程序助手中,它就会进入控制器.但是模型中通常不需要应用程序助手.那么,您将要在模型和控制器中使用的通用代码放在哪里?

Suppose I have a function trim_string(string) that I want to use throughout my Rails app, in both a model and a controller. If I put it in application helper, it gets into the controller. But application helper isn't required from within models typically. So where do you put common code that you'd want to use in both models and controllers?

回答特定问题您将要在模型和控制器中使用的公共代码放在哪里?":

In answer to the specific question "where do you put common code that you'd want to use in both models and controllers?":

放在lib文件夹中.lib 文件夹中的文件将被加载,其中的模块将可用.

Put it in the lib folder. Files in the lib folder will be loaded and modules therein will be available.

更详细地,使用问题中的具体示例:

In more detail, using the specific example in the question:

# lib/my_utilities.rb

module MyUtilities
  def trim_string(string)
    do_something
  end    
end

然后在您想要的控制器或模型中:

Then in controller or model where you want this:

# models/foo.rb

require 'my_utilities'

class Foo < ActiveRecord::Base
  include MyUtilities

  def foo(a_string)
    trim_string(a_string)
    do_more_stuff
  end
end

# controllers/foos_controller.rb

require 'my_utilities'

class FoosController < ApplicationController

  include MyUtilities

  def show
    @foo = Foo.find(params[:id])
    @foo_name = trim_string(@foo.name)
  end
end