Rails 3 - IF a variable contains a part of the URL?
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 /b开发者_开发问答ooks/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");
}
});
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
if params[:urlpath]
if params[:urlpath].to_s.index('/projects') == 0
#...
end
end
Example:
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
精彩评论