Question

in one rails 3.2 app, I am doing this.

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

which works fine. except for the Asset pipeline. I need these parameters to be appended to all app urls, including css, js, images.

in a separate rails 3.2 app. for a strange reason I ignore. the same url_options did not work. not only for assets, but did not work at all. I had to do the following instead.

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

which does not work for assets either. I'm puzzled. anyone would know of a solution?

thanks

Was it helpful?

Solution

there you go ! you can monkey patch Sprockets to include your url option helper...

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top