Rails 3.2 asset_host setting ignored

匿名 (未验证) 提交于 2019-12-03 08:54:24

问题:

My production environment -

# Code is not reloaded between requests   config.cache_classes = true   config.assets.enabled = true    # Full error reports are disabled and caching is turned on   config.consider_all_requests_local       = false   config.action_controller.perform_caching = true    # Disable Rails's static asset server (Apache or nginx will already do this)   config.serve_static_assets = true   config.static_cache_control = "public, max-age=31536000"    # Compress JavaScripts and CSS   config.assets.compress = true   config.assets.js_compressor  = :uglifier   #config.assets.css_compressor = :yui    # Don't fallback to assets pipeline if a precompiled asset is missed   config.assets.compile = true    # Generate digests for assets URLs   config.assets.digest = true    # See everything in the log (default is :info)   config.log_level = :warn   config.log_tags = [:remote_ip, lambda { |req| Time.now }]    # Enable serving of images, stylesheets, and JavaScripts from an asset server   ActionController::Base.asset_host = Proc.new { |source|     unless source.starts_with?('/stylesheets' || '/javascripts')       "//dddd.cloudfront.net/"     end    } 

However, when I using image_tag it still returns me '/assets..' relative url and not absolute url to the asset host.

irb(main):034:0> helper.image_tag('noimage.gif') => "<img alt=\"Noimage\" src=\"/assets/noimage.gif\" />" irb(main):035:0> helper.image_path('noimage.gif') 

I can not seem to figure what might be missing. I even tried doing simple config.asset_host setting, and still it does not recognize the setting.

回答1:

Have you tried setting the designated config?

config.action_controller.asset_host = 'https://abcd.cloudfront.net' 

Not sure it works with protocol relative urls. I simply use https in my apps.

It might also be worth noting that action mailer has a similar setting:

config.action_mailer.asset_host = 'https://abcd.cloudfront.net' 


回答2:

There's something odd in Rails configuration. According to the documentation asset_host is supposed to hold just the host part ('yoursite.com'). I resolved with an helper:

module EmailsHelper    def email_image_tag(src)      protocol = ActionMailer::Base.default_url_options[:protocol] || 'http'     image_tag asset_path(src, protocol: protocol)   end  end 

Configure it in your mailer:

class EmailNotificationsMailer < ActionMailer::Base    add_template_helper(EmailsHelper)   ...  end 

There's no way to force image_tag to use a URL other than to pass a URL to it.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!