开发者

link_to_unless_current for subURLs in Rails

开发者 https://www.devze.com 2023-01-01 01:51 出处:网络
I\'m looking for a way to use something similar to link_to_unless_current but for sub URLs, so for instance for both these URLs:

I'm looking for a way to use something similar to link_to_unless_current but for sub URLs, so for instance for both these URLs:

/entity_name/
/entity_name/123

it will not result as a link. How can I achieve that in Rails?

UPD: Resolved it my own custom way, please Ruby savvy let me know if it's good.

module ApplicationHelper

  def link_to_unless_current_or_sub(name, options = {}, html_options = {}, &block)
    link_to_unless current_page_or_sub?(options), name, options, html_options, &block
  end

priva开发者_Python百科te

  def current_page_or_sub?(options)
    url_string = CGI.unescapeHTML(url_for(options))
    request = @controller.request
    if url_string.index("?")
      request_uri = request.request_uri
    else
      request_uri = request.request_uri.split('?').first
    end

    request_uri.starts_with?(url_string)
  end

end

Usage:

<%= link_to_unless_current_or_sub("Users", users_path) %>


i don't think such helper method exist

you have to write something like following

<% if params[:id] %>
       "Home"
<% else %>
       <%= link_to "Home", { :action => "index" }) %>
<% end %>


Works in Rails 3.2 with some minor adjustments

def current_page_or_sub?(options)
  url_string = CGI.unescapeHTML(url_for(options))
  if url_string.index("?")
    request_url = request.fullpath
  else
    request_url = request.fullpath.split('?').first
  end
  request_url.starts_with?(url_string)
end
0

精彩评论

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