Is there a way to check if part of the URL contains a certain string

ε祈祈猫儿з 提交于 2019-12-07 04:29:22

问题


Is there a way to check if part of the URL contains a certain string:

Eg. <% if current_spree_page?("/products/*") %>, where * could be anything?


回答1:


I tested, and gmacdougall's answer works, I had already found a solution though.

This is what I used to render different layouts depending on what the url is:

  url = request.path_info
  if url.include?('products')
    render :layout => 'product_layout'
  else
    render :layout => 'layout'
  end

The important thing to note is that different pages will call different methods within the controller (eg. show, index). What I did was put this code in its own method and then I am calling that method where needed.




回答2:


If you are at a place where you have access to the ActionDispatch::Request you can do the following:

request.path.start_with?('/products')



回答3:


You can use include? method

my_string = "abcdefg" if my_string.include? "cde" puts "String includes 'cde'" end`

Remember that include? is case sensetive. So if my_string in the example above would be something like "abcDefg" (with an uppercase D), include?("cde") would return false. You may want to do a downcase() before calling include?()




回答4:


The other answers give absolutely the cleanest ways of checking your URL. I want to share a way of doing this using a regular expression so you can check your URL for a string at a particular location in the URL.

This method is useful when you have locales as first part of your URL like /en/users.

module MenuHelper
  def is_in_begin_path(*url_parts)
    url_parts.each do |url_part|
      return true if request.path.match(/^\/\w{2}\/#{url_part}/).present?
    end
    false
  end
end

This helper method picks out the part after the second slash if the first part contains 2 word characters as is the case if you use locales. Drop this in your ApplicationController to have it available anywhere.

Example:

is_in_begin_path('users', 'profile')

That matches /en/users/4, /en/profile, /nl/users/9/statistics, /nl/profile etc.



来源:https://stackoverflow.com/questions/29222972/is-there-a-way-to-check-if-part-of-the-url-contains-a-certain-string

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!