views:

78

answers:

3

Hello, i have a variable like /projects/3/blah blah or /projects/3 or just /projects

What I'd like to do is have an IF statement in Rails like this:

IF urlPath contains /projects proceed

Does Rails / Ruby have a method for that? Also, likely it shouldn't have a false positive for something like /books/projects or /authors/mr-projects/ etc...

jquery posting to Rails which them does the above evaluation:

$.ajax({
    url: '/navigations/sidenav',
    //data:{"urlpath":urlpath}, // 
    data: "urlpath=" + urlpath,
    success: function(e){
        $("#sideNav-container").slideDown("slow");
    }
});
+1  A: 
if params[:urlpath]
   if params[:urlpath].to_s.index('/projects') == 0 
       #...
   end
end

Example:

alt text

Jacob Relkin
Rails wasn't happy with that? "You have a nil object when you didn't expect it!"
AnApprentice
Nice example image, Is this what you were thinking? "<% if @urlPath.index('/projects') == 0 %>"
AnApprentice
@TheApprentice, Show us the context in which you are executing this code. My identifier `urlPath` may be different than the one that you have.
Jacob Relkin
@TheApprentice, Yes.
Jacob Relkin
hmmm, that gives an error. "You have a nil object when you didn't expect it!You might have expected an instance of Array. The error occurred while evaluating nil.index"... I'll update my question with the jquery I'm using to post to Rails 3 so you can see it...
AnApprentice
@TheApprentice, Try my updated answer.
Jacob Relkin
AnApprentice
+1  A: 

In rails you can use starts_with? to do such things:

if params[:urlpath].starts_with? "/projects"
  #...
end

Of course this fails when the hash lookup evaluates to nil. This is where the try method comes in handy:

if params[:urlpath].try(:starts_with?, "/projects")
  #...
end
hurikhan77
A: 
if params[:urlpath].to_s.match %r{^/projects}
  ...
end

or you could do it with js

'/projects'.match(/^\/projects/)
#=> ["/projects"]
'/books/projects'.match(/^\/projects/)
#=> null

Maybe you wan't to check if some view has been rendered from a specified controller

if params[:controller] == 'projects'
   ...
end
Macario