How to mixin and call link_to from controller in Rails?

Solution 1:

Compatible with Rails 3,4 and 5:

view_context.link_to

Solution 2:

This doesn't really answer your question but there is an easier way

For Rails 5, use the helpers proxy

helpers.link_to '...', '...'

For Rails 3 and 4, since you are using the helper from a controller you can use the view_context

# in the controller code
view_context.link_to '...', '...'

# instead of using your mixin code 
link_to '...', '...'

For Rails 2, since you are using the helper from a controller you can actually access the @template member variable of the controller, the @template is the view and already has the UrlHelper mixed in

# in the controller code
@template.link_to '...', '...'

# instead of using your mixin code 
link_to '...', '...'

if you need to use the urlhelper from code other than the controller, your solution is probably the way to go

Solution 3:

You can do it like this:

ActionController.helpers.link_to("Click Me!", awesome_path)

But really, a better place to generate that link might be in a helper module where UrlHelper and other view-related helpers are already included.

[update]

This approach is outdated and no longer works.