Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@xaviershay
Created May 19, 2011 21:43
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xaviershay/981829 to your computer and use it in GitHub Desktop.
Save xaviershay/981829 to your computer and use it in GitHub Desktop.
Access helper methods outside controllers and views
class ApplicationController < ActionController::Base
# Provide access to helper methods from outside controllers and views,
# such as in Presenter objects. Rails provides ActionController::Base.helpers,
# but this does not include any of our application helpers.
def self.all_helpers
@all_helpers_proxy ||= begin
# Start with just the rails helpers. This is the same method used
# by ActionController::Base.helpers
proxy = ActionView::Base.new.extend(_helpers)
# url_for depends on _routes method being defined
proxy.instance_eval do
def _routes
Rails.application.routes
end
end
# Import all named path methods
proxy.extend(Rails.application.routes.named_routes.module)
# Load all our application helpers to extend
modules_for_helpers([:all]).each do |mod|
proxy.extend(mod)
end
proxy
end
end
end
@rwilcox
Copy link

rwilcox commented Sep 2, 2011

+1, this is much better than other approaches I found online!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment