【问题标题】:How could the asset pipeline use url_options to automatically append parameters like url_for and link_to?资产管道如何使用 url_options 自动附加 url_for 和 link_to 等参数?
【发布时间】:2013-06-19 13:09:46
【问题描述】:

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

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

效果很好。除了资产管道。 我需要将这些参数附加到所有应用程序 url,包括 css、js、图像。

在单独的 rails 3.2 应用程序中。出于一个奇怪的原因,我忽略了。 相同的 url_options 不起作用。不仅适用于资产,而且根本不起作用。 我必须改为执行以下操作。

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

这也不适用于资产。 我很困惑。有人会知道解决方案吗?

谢谢

【问题讨论】:

  • 有谁知道这两种方法的区别,请澄清。为什么一个在某些情况下工作,而有时另一个是必需的?两者之间还有其他区别吗?

标签: ruby-on-rails assets url-parameters url-for


【解决方案1】:

你去吧!您可以修改 Sprockets 以包含您的 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

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多