4

i'm working on refinerycms, trying to add preview feature to news like pages, i'm trying to include my own helper to a controller, 'include' does not works, but 'helper' works.

sample code:

module Refinery
  module News
    module Admin
      class PreviewController < ActionController::Base
        #include LayoutHelper # not ok
        helper LayoutHelper # Ok
      end
    end
  end
end

i've read the api, helper is working like 'require and include', but i don't know the real difference here.

thanks !

dfang
  • 1,366
  • 15
  • 41

1 Answers1

5

helper LayoutHelper does include LayoutHelper, but it is included directly in the template class.

while include LayoutHelper, the module is included in the controller class.

You could check the source of helper:

# File actionpack/lib/abstract_controller/helpers.rb, line 93
def helper(*args, &block)
  modules_for_helpers(args).each do |mod|
    add_template_helper(mod)
  end

  _helpers.module_eval(&block) if block_given?
end
xdazz
  • 158,678
  • 38
  • 247
  • 274
  • I just saw this answer and I have a follow up if you don't mind xdazz. If Rails already 'includes' the files found in the helper directory in the app/views directory why would you need to use the keyword 'helper' in the controller? I would think you would always want to include (in this case LayoutHelper) in the controller. LayoutHelper should already be accessible in the template by default. – Dan Rubio Apr 07 '15 at 18:44
  • In answer to the question above, you might have a module defined NOT in /helpers but somewhere else like /lib then it wouldn't be automatically imported by Rails. – Seth Jeffery Dec 21 '16 at 08:38