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

4

7

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?

Gur answered 24/3, 2015 at 0:37 Comment(0)
G
16

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.

Gur answered 25/3, 2015 at 0:35 Comment(1)
I don't think if the include? does the work right. What if the keyword "products" is elsewhere in the path? For example, if the agenda with the name "user_projects" exists, then it will match this value too.Palmy
O
8

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

request.path.start_with?('/products')
Occident answered 24/3, 2015 at 13:29 Comment(0)
N
2

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?()

Northwesterly answered 26/3, 2015 at 17:22 Comment(0)
L
2

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.

Leanneleanor answered 9/8, 2016 at 9:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.