38

i am using refinery cms at the moment. I created an engine and with it some helpers in app/helpers/admin/. now i would like to use those helpers in my frontend view (ie. app/views/myapp/index) as well. but i can not...undefined methode error. what do i have to do short of copying the whole thing to app/helpers/? the helper looks like this

module Admin
    module myHelper
        def somefunc
        end
    end
end

so is it possible to use somefunc outside of the Admin module?

Hans
  • 383
  • 1
  • 3
  • 4
  • +1 good question. I struggled with this for a few minutes last night before bed. Nice to come in and find the exact question/answer I was looking for... – jaydel May 20 '11 at 12:42

3 Answers3

62

The "Rails way" to include a helper from a non-standard path in a view is to use the .helper method within your controller.

class MyController < ApplicationController
    helper Admin::MyHelper
    ...
end

http://apidock.com/rails/AbstractController/Helpers/ClassMethods/helper

Christoph Petschnig
  • 4,047
  • 1
  • 37
  • 46
bobics
  • 2,301
  • 2
  • 23
  • 25
28

In your application_helper.rb:

module ApplicationHelper
  include Admin::MyHelper
end

This will import those helper methods into the ApplicationHelper, thus making them available in your views. You could do this in any of your helpers really.

d11wtq
  • 34,788
  • 19
  • 120
  • 195
  • Thanks that works. But why does it not work when i just include it in MyHelper...like this `module MyHelper include Admin::MyHelper` why do i have to go over application_helpers when it is in the same engine? – Hans May 20 '11 at 12:24
  • 1
    Rails doesn't include any view helper modules deeper than the top-level namespace, you need to include them yourself. – d11wtq May 20 '11 at 12:28
  • Hmm, where is `my_helper.rb` ? – d11wtq May 20 '11 at 12:28
  • ahh allright i found the error in my head. thanks a lot for clearing that up...have a great day! – Hans May 20 '11 at 12:36
  • @d11wtq: Your second comment points at the origin of the problem, could you add it to the answer? thanks. – tokland Jul 30 '13 at 11:37
  • What if I want to incude just a single method from the helper? – przemek Feb 27 '16 at 09:11
0

You might try to use the full object reference like Admin::myHelper::somefunc to call somefunc from outside the Admin module.

arnep
  • 5,971
  • 3
  • 35
  • 51