【发布时间】:2014-03-20 16:54:42
【问题描述】:
假设我有一个函数 trim_string(string) 我想在我的 Rails 应用程序中使用,包括模型和控制器。如果我把它放在应用程序助手中,它就会进入控制器。但是模型中通常不需要应用程序助手。那么,您将希望在模型和控制器中使用的通用代码放在哪里?
【问题讨论】:
标签: ruby-on-rails
假设我有一个函数 trim_string(string) 我想在我的 Rails 应用程序中使用,包括模型和控制器。如果我把它放在应用程序助手中,它就会进入控制器。但是模型中通常不需要应用程序助手。那么,您将希望在模型和控制器中使用的通用代码放在哪里?
【问题讨论】:
标签: ruby-on-rails
回答具体问题“您将希望在模型和控制器中使用的通用代码放在哪里?”:
把它放在lib文件夹中。 lib 文件夹中的文件将被加载,其中的模块将可用。
更详细地说,使用问题中的具体示例:
# lib/my_utilities.rb
module MyUtilities
def trim_string(string)
do_something
end
end
然后在你想要的控制器或模型中:
# 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
【讨论】:
看起来您希望在 String 类上有一个方法来“修剪”自身,而不是 trim_string 函数,对吧?你不能用条带法吗? http://www.ruby-doc.org/core-2.1.0/String.html#method-i-strip
您可以在初始值设定项上向字符串类添加新方法,检查此In Rails, how to add a new method to String class?
class String
def trim
do_something_and_return_that
end
def trim!
do_something_on_itself
end
end
这样你就可以做到:
s = ' with spaces '
another_s = s.trim #trim and save to another
s.trim! #trim itself
但是检查 String 类,看起来你已经有了你需要的东西
【讨论】: