简体   繁体   中英

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!

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. 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:

class SomeControllerTest < ActionController::TestCase
  include Foo

which made it available to the controller... somehow.

Removing the include Foo made the test fail as well.

To make the controller work, I changed

normalize "a string"

to

self.normalize "a string"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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