简体   繁体   English

如何将模块混合到Rails 3控制器中

[英]How do you mixin a module into a Rails 3 controller

I have a module 我有一个模块

module Foo
  def normalize name
    # modify and return
  end
end

I can mix it in to a model just fine... 我可以将它混合到一个模型中就好了......

class Something
  include Foo
end

Something.new.normalize "a string" # works

And try to mixin to a controller... 并尝试混合到控制器......

class SomeController < ApplicationController
  include Foo

  def some_action
    normalize "a string"
  end
end

SomeController#some_action # Works in a functional test, but not within rails server! SomeController#some_action#在功能测试中工作,但不在rails服务器中!

I've tried various forms of the module, extending ActiveSupport::Concern, adding an included block and changing normalize to a class method, but I get the same results. 我已经尝试了各种形式的模块,扩展了ActiveSupport :: Concern,添加了一个包含的块并将normalize更改为类方法,但我得到了相同的结果。 Why would this work in a functional test, but not outside of it? 为什么这会在功能测试中起作用,但不能在它之外?

I get the feeling I'm just missing something easy. 我感觉我只是错过了一些简单的事情。

The reason it "worked" in the test was that the test also included the module and invoked the normalize method: 它在测试中“工作”的原因是测试还包括模块并调用normalize方法:

class SomeControllerTest < ActionController::TestCase
  include Foo

which made it available to the controller... somehow. 这让它可以提供给控制器...不知何故。

Removing the include Foo made the test fail as well. 删除include Foo也使测试失败。

To make the controller work, I changed 为了使控制器工作,我改变了

normalize "a string"

to

self.normalize "a string"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM