在 Rails 中,把对控制器和模型有用的函数放在哪里 [英] In Rails, where to put useful functions for both controllers and models

查看:28
本文介绍了在 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

这篇关于在 Rails 中,把对控制器和模型有用的函数放在哪里的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆