theschmitzer
theschmitzer

Reputation: 12860

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.

Upvotes: 1

Views: 758

Answers (1)

theschmitzer
theschmitzer

Reputation: 12860

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"

Upvotes: 4

Related Questions