假设我有一个函数 trim_string(string) 我想在我的 Rails 应用程序中使用,包括模型和 Controller 。如果我把它放在应用程序助手中,它就会进入 Controller 。但是模型中通常不需要应用程序助手。那么,您将希望在模型和 Controller 中使用的通用代码放在哪里呢?
最佳答案
回答特定问题“您将希望在模型和 Controller 中使用的通用代码放在哪里?”:
把它放在lib文件夹中。 lib 文件夹中的文件将被加载,其中的模块将可用。
更详细地说,使用问题中的具体示例:
# lib/my_utilities.rb
module MyUtilities
def trim_string(string)
do_something
end
end
然后在您想要的 Controller 或模型中:
# 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
关于ruby-on-rails - 在 Rails 中,在哪里放置对 Controller 和模型有用的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21896093/