ruby-on-rails 资产管道如何使用url_options来自动附加url_for和link_to之类的参数?

yeotifhr  于 2023-02-26  发布在  Ruby
关注(0)|答案(1)|浏览(118)

在一个rails 3.2应用程序中,我正在这样做。

def url_options
  {
    :p1 => value1,
    :p2 => value2
  }.merge(super)
end

这工作正常。除了资产管道。我需要这些参数被附加到所有的应用程序网址,包括css,js,图像。
在一个单独的rails 3.2应用程序中。出于一个奇怪的原因,我忽略了。相同的url_options不起作用。不仅对资产,而且根本不起作用。我不得不做以下事情来代替。

Rails.application.routes.default_url_options[:p1] = value1

这对资产也不起作用。我很困惑。有人知道解决办法吗?
谢谢

ljsrvy3e

ljsrvy3e1#

好了!你可以猴子补丁链轮包括你的url选项助手...

module Sprockets
  module Helpers
    module RailsHelper
      def asset_path_with_url_options(source, options = {})
        uri = Addressable::URI.parse(asset_path_without_url_options(source, options))
        default_url_options = url_options.dup.delete_if { |k,v|
          [:host, :port, :protocol, :_path_segments, :script_name].include?(k)
        }
        uri.query_values = default_url_options.merge(uri.query_values || {})
        uri.to_s
      end

      alias_method_chain :asset_path, :url_options
      alias_method :path_to_asset, :asset_path_with_url_options # aliased to avoid conflicts with an asset_path named route
    end
  end
end

class ApplicationController < ActionController::Base
  protect_from_forgery

  # anything using link_to, url_for, etc. uses this automatically.
  def url_options
    {
      :k1 => v1,
      :k2 => v2
    }.merge(super)
  end

end

相关问题