开发者

AssetTagHelper::image_path outside views

开发者 https://www.devze.com 2023-01-17 23:13 出处:网络
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

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开发者_如何学C config.asset_host but config is nil.

How can I successfully call image_path from outside views?


Use view_context to access those helper methods that are available in the view.

You can call image_path like this from the controller.

view_context.image_path "my_image.png"


For Rails 3 please checkout the much cleaner solution here How can I use image_path inside Rails 3 Controller


This solution, posted by Mason Jones, works for me.

In your application controller:

def self.tag_helper
  TagHelper.instance
end

class TagHelper
  include Singleton
  include ActionView::Helpers::TagHelper
  include ActionView::Helpers::AssetTagHelper
end

Then you can do the following kind of thing, or whatever else you need.

active_scaffold :mything do |config|
  config.columns = [:name, :number, :active, :description]
  config.update.link.label = tag_helper.image_tag('document_edit.png', :width => "30")
  config.delete.link.label = tag_helper.image_tag('document_delete.png', :width => "30")
  config.show.link.label = tag_helper.image_tag('document.png', :width => "30")
  list.sorting = {:name => 'ASC'}
end

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.

0

精彩评论

暂无评论...
验证码 换一张
取 消