Misha Moroshko
Misha Moroshko

Reputation: 171479

How to use a custom helper via the "helper" method in Rails 3?

I'm trying to create a custom helper like this:

# app/controllers/my_controller.rb
class MyController < ApplicationController
  helper :my
  def index
    puts foo
  end
end

# app/helpers/my_helper.rb
module MyHelper
  def foo
    "Hello"
  end
end

But, I got the following error:

undefined local variable or method `foo' for #<MyController:0x20e01d0>

What am I missing ?

Upvotes: 3

Views: 2237

Answers (3)

user3345580
user3345580

Reputation: 76

How about just including the helper as a mixin in the controller...

class MyController < ApplicationController
  include MyHelper

  def index
    puts foo
  end
end

Upvotes: 0

apneadiving
apneadiving

Reputation: 115541

Generally, I do the opposite: I use controller methods as helpers.

class MyController < ApplicationController
  helper_method :my_helper

  private 
  def my_helper
    "text"
  end
end

Upvotes: 3

DanneManne
DanneManne

Reputation: 21180

Helpers are accessed from the views, not the controllers. so if you try to put the following inside your index template it should work:

#my/index.html.erb
<%= foo %>

If you do want to access something from the controller, then you should use the include syntax instead of helper, but do not name it like a helper module in that case.

Upvotes: 1

Related Questions