In both url_for and link_to, the :only_path param can be used to
determine whether the link url used is complete with hostname and path,
or just has the path (a kind of relative url).
However, in url_for it defaults to false (urls with hostnames), and in
link_to it defaults to true ( urls without hostnames, just paths).
Is there any reason for this discrepency? To me, it violates the
principle of least surprise.
Is there any way for me to make Rails default to false for link_to also?
I have a case where the urls without hostnames are messing something up,
and I really don’t want to have to go in and add :only_path to every
single call to link_to. I really want to be able to change the default
behavior globally. Anyone know if there’s a good way to do that?
Thanks!
Jonathan
Is there any way for me to make Rails default to false for link_to also?
I have a case where the urls without hostnames are messing something up,
and I really don’t want to have to go in and add :only_path to every
single call to link_to. I really want to be able to change the default
behavior globally. Anyone know if there’s a good way to do that?
Something like this (untested, but this is pretty close):
module ActionView
module Helpers
module UrlHelper
alias_method :link_to_orig :link_to
def link_to(name, options = {}, html_options = nil,
*parameters_for_method_reference)
link_to(name, {:only_path => false}.merge(options),
html_options, paramaters_for_method_reference)
end
end
end
end
Is there any way for me to make Rails default to false for link_to also?
alias_method :link_to_orig :link_to
def link_to(name, options = {}, html_options = nil, *parameters_for_method_reference)
link_to(name, {:only_path => false}.merge(options), html_options, paramaters_for_method_reference)
Bah! the above “link_to” should be “link_to_orig”. Heh.
Cool, thanks. That got me thinking. What I actually ended up doing
instead is over-ride url_for in application_helper, to respect a @ivar.
def url_for(options={}, *parameters_for_method_reference)
options[:only_path] = false if @urls_with_hostname &&
options[:only_path].nil?
super(options, parameters_for_method_reference)
end
After I thought of this, this seems to work nicely. Defaults both
url_for and link_to in views to :only_path=false (:url_for in controller
already defaults to this, go figure), can be controlled on an
action-by-action (or even block-by-block) basis, still respects
:only_path passed in manually in call if present.
Is there any reason not to do what I’m doing there?
Jonathan
Philip H. wrote:
Is there any way for me to make Rails default to false for link_to also?
alias_method :link_to_orig :link_to
def link_to(name, options = {}, html_options = nil, *parameters_for_method_reference)
link_to(name, {:only_path => false}.merge(options), html_options, paramaters_for_method_reference)
Bah! the above “link_to” should be “link_to_orig”. Heh.