Rails : Access view/route helpers from anywhere (Model / Services)

Normally we always need to access route and view helper methods from anywhere in our code base.

View Helpers

In your model, you can do something like the following:

ApplicationController.helpers.your_helper_method

OR

YourController.helpers.your_helper_method

 

In console this will work in Rails ~= 2.3 and >= 3.1.0

app.post_path

# If namespacing is used in routes
app.spree.product_path(Spree::Product.first)
 

Path/Route helpers

class HelperWrapper
  include Rails.application.routes.url_helpers
end
  HelperWrapper.new.admin_path

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s