0

I am confused about the rails Helper scope.

I defined a testpage method in PagesHelper

module PagesHelper
  def testpage
    "testpagehelper"
  end
end

But why I can use the testpage method in views/users/index.html.erb

<h1><%= testpage %> </h1>

I suppose the testpage only used in views/pages/index.html.erb?

I think the helper method scope is too broad.

And there is a problem if I defined the same method in the UsersHelper.

module UsersHelper
  def testpage
    "testuserhelper"
  end
end

there is two testpage in the helper,but the resutl is the view/pages/index.html and the view/users/index.html all use the "testpage" in the UsersHelper?Why?

wcc526
  • 3,915
  • 2
  • 31
  • 29

2 Answers2

1

New Rails apps use helper :all in ApplicationController -- which means that all helpers are loaded in all controllers that inherit from ApplicationController. I agree that this is too broad of a scope. So you should change that to helper :application and then let each controller pull in just its own helper. Note that each controller will pull in the helper that has its namesake automatically, though, so you don't have to include helper :user in UsersController, for example.

pdobb
  • 17,688
  • 5
  • 59
  • 74
  • sorry,my problem is the helper scope is all views,even unrelated views. – wcc526 May 20 '14 at 04:21
  • I understand and that's the problem I was referring to above too. The controller is respopnsible for pulling in helpers which are then made available to the views for that request. So if you don't load ALL helpers for every request then you won't get all helper methods available in every view. I found this SO post which says the same thing: http://stackoverflow.com/questions/1179865/why-are-all-rails-helpers-available-to-all-views-all-the-time-is-there-a-way-t -- but apparently this is a setting now in Rails >= 3.1. – pdobb May 20 '14 at 12:55
  • thank you very much! I think the DHH thought it is more convenient if the helper is available to all the views,in fact the method 's collide is not big problem if compare to the helper 's DRY. – wcc526 May 20 '14 at 13:01
0

The different helper modules are just to help with organizing your method. You can use PageHelper in non-related views but should you? It's up to the programmer to decide.

Chris Ledet
  • 11,458
  • 7
  • 39
  • 47