开发者

Automatically append parameters to *_url or *_path methods (Rails)

开发者 https://www.devze.com 2023-01-25 14:31 出处:网络
I have a particular set of views relating to one of my controllers, whereby I want any call to *_path or *_url to append a set of parameters.

I have a particular set of views relating to one of my controllers, whereby I want any call to *_path or *_url to append a set of parameters.

Is there some magic method I can override that will let me do this? I have no idea where in the Rails code the *_path or *_url methods are even handled.

Edit for clarity: I'm looking for a way to do this such that I don't have to modify every link in every view where this needs to occur. I don't want every coder who touches this set of views to have to remember to append a parameter to every link they add to the pa开发者_StackOverflowge. The same parameter should be appended automatically. I consider a change to the *_url or *_path call a failure. Similarly, having to override every *_url or *_path call is considered a failure since a new method would have to be added/removed whenever a new link is added/removed.


You can do this by overriding url_for since all the routing methods call it.

module ApplicationHelper
  def url_for(options = {})
    options.reverse_merge!(@extra_url_for_options) if @extra_url_for_options
    super
  end
end

Now all you need to do is use a before_filter to set @extra_url_for_options to a hash to force all urls.

class MyController < ApplicationController
  before_filter do { @extra_url_for_options = { :format => 'html' } }
end

Note that this will force all links to use the extra options.


Thanks to Samuel's answer, I was able to create a final working solution via a new helper, which I've included below.

module ExampleHelper
  def url_for(options={})
    options = case options
    when String
      uri = Addressable::URI.new
      uri.query_values = @hash_of_additional_params

      options + (options.index('?').nil? ? '?' : '&') + uri.query
    when Hash
      options.reverse_merge(@hash_of_additional_params)
    else
      options
    end

    super
  end
end


You can try to use the with_options method. In your view you can do something like

<% with_options :my_param => "my_value" do |append| -%>

  <%= append.users_path(1) %>

<% end %>

Assuming you have the users_path of course. my_param=value will be appended to the url


You could make a helper method:

def my_path(p)
  "#{p}_path all the parameters I want to append"
end

and in the view use

<%= eval(my_path(whatever)) %>

Eval with give you dynamic scope, so every variable available in your view can be used in the helper. If your parameters are constant you can get rid of eval calls.

0

精彩评论

暂无评论...
验证码 换一张
取 消