Rails 3.1 absolute URL to an image

前端 未结 7 837
孤街浪徒
孤街浪徒 2020-12-08 14:27

I\'m using Rails 3.1. I\'m trying to figure this out, and to my surprise, it is starting to seem that rails does not come with this method at all. Maybe im wrong.

Ca

相关标签:
7条回答
  • 2020-12-08 14:41

    In my config/environments/*.rb I already have this tailored for each environment:

    config.domain = 'mysite.dev'
    

    So it was a simple matter of adding

    config.action_controller.asset_host = "http://" + config.domain
    

    to each file. Then asset_path will miraculously behave as if it were asset_url.

    0 讨论(0)
  • 2020-12-08 14:41

    Example folder structure.

    app/
       assets/
          flags/
             32x32/
                en.png
             256x256/
                en.png
    

    If you want to generate absolute flag image path we can add in to our ApplicationHelper two methods:

    module ApplicationHelper
    
      # Generate flag path by locale
      # - locale. Can be "en", "it", etc.
      # - flag_size. Will be used to set folder size. Folder size can be "32x32", "256x256".
      # Return flag image path. Path will absolute
      def generate_flag_path_by_locale(locale, folder_size = "32")
        folder = "#{flag_size}x#{flag_size}"
        domain_absolute_path = generate_domain_absolute_path
        flag_path = ("#{domain_absolute_path}/assets/flags/#{folder}/#{locale}.png")
    
        return flag_path
      end
    
      # Generate domain absolute path
      def generate_domain_absolute_path
        request_protocol = request.protocol
        request_host_with_port = request.host_with_port
        domain_absolute_path = request_protocol + request_host_with_port
    
        return domain_absolute_path
      end
    end
    

    Into our apps/view/products.html.erb. We must to call only:

    <% flag_path = generate_flag_path_by_locale("en") %> 
    

    Final result:

    http://my_domain.com:3000/assets/flags/32x32/en.png

    0 讨论(0)
  • 2020-12-08 14:45

    put this in application_helper.rb

    def asset_url asset
      "#{request.protocol}#{request.host_with_port}#{asset_path(asset)}"
    end
    

    then you can use asset_url in your views.

    0 讨论(0)
  • 2020-12-08 14:46

    For Rails 4, and maybe earlier, use:

    config.action_mailer.asset_host = 'https://assets.com'
    

    per https://github.com/fphilipe/premailer-rails/issues/16

    0 讨论(0)
  • 2020-12-08 14:49

    You need to use 'asset_url' instead *asset_path*.

    Bcz '_path' always return relative path and '_url' will return absolute url.

    0 讨论(0)
  • 2020-12-08 14:52

    See the Using asset hosts section in the documentation. You need to specify an asset_host. You can also construct it dynamically from the request chaining "#{request.protocol}#{request.host_with_port}"

    0 讨论(0)
提交回复
热议问题