Supposedly, ActionController::Base.helpers
acts like a proxy for accessing helpers outside views. However many of the methods defined there rely on controller variables and I'm unable to succesfully call:
ActionController::Base.helpers.image_path("my_image.png")
>> TypeError Exception: can't convert nil into String
Digging at the source I see compute_asset_host
method is trying to access config.asset_host
but config
is nil
.
How can I successfully call image_path
from outside views?
This solution, posted by Mason Jones, works for me.
In your application controller:
Then you can do the following kind of thing, or whatever else you need.
You're creating a Singelton instance of TagHelper in your ApplicationController. This gives you the helpers wherever you need them. He explains it in his post.
Also, I use this to extend my models (to create a more flexible image_tag helper that returns a default image if there's no image present -- e.g. person.small_image is an instance variable of the person model, which uses tag_helper). To do that I've put the same code in a Monkey Patch initializer that extends ActiveRecord::Base. I then call ActiveRecord::Base.tag_helper from within my models. This is a bit messy, but I'm new to rails. There's probably a cleaner way.
Hope that helps.
For Rails 3 please checkout the much cleaner solution here How can I use image_path inside Rails 3 Controller
Use
view_context
to access those helper methods that are available in the view.You can call
image_path
like this from the controller.