APJ
APJ

Reputation: 245

syntax for everything after string? (Ruby)

I want to make the following code much shorter. I need to make it so that everything after /users/1/... is okay and /users/1 is okay. How can I achieve this? Thanks!

<%if request.path == "/users/#{current_user.id}" or request.path == "/users/#{current_user.id}/listeners" or request.path == "/users/#{current_user.id}/listening" or request.path == "/users/#{current_user.id}/discovered" %>

I guess in CSS it's similar to ^=

Upvotes: 0

Views: 79

Answers (2)

Marek Lipka
Marek Lipka

Reputation: 51151

How about params comparison? It all probably happens within users resource, so this segment of url will be stored in params[:id] and we can compare it with current user id doing:

<% if params[:id].to_i == current_user.id %>

or, as you probably set @user variable in this controller:

<% if @user == current_user %>

Upvotes: 2

Matt
Matt

Reputation: 14038

You can use starts with? to check if the beginning of the string matches 'users/1' etc, or you can use .include? to find the string anywhere.

# starts with:
<%if request.path.starts_with?("/users/#{current_user.id}/") %>
# include:
<%if request.path.include?("/users/#{current_user.id}/") %>

If you are trying to find out if the user is on a users controller action then you can check the controller param value instead:

<% if params[:controller] == 'users' %>

If you want to know if the user viewing the page is the same as the user being viewed (eg. a user looking at their own account page), you can compare the current user to the @user object that your methods instantiate:

<% if current_user == @user %>

Upvotes: 1

Related Questions