I am trying to parse URLs. For example where I am trying to pull out:
~/locations/1 => [locations,1]
~/locations/1/comments => [locations,1]
~/locations/1/comments/22 => [locations,1]
~/locations/1/buildings/3 => [buildings,3]
~/locations/1/buildings/3/comments => [buildings,3]
~/locations/1/buildings/3/comments/34 => [buildings,3]
The format is pretty consistent. I started with arrays but it seems to still fail:
@request_path = request.path.downcase.split('/')
@comment_index = @request_path.index("comments").to_i
if @comment_index > 0
@request_path = @request_path.drop_while { |i| i.to_i >= @comment_index }
end
resource, id = @request_path.last(2)
I added the downcase just incase someone manually typed in an uppercase URL. The drop_while seems to not be working.
What kind of output you have after processing your code?
Edited
Your problem is that you convert element
to_iand it is0. But you want to compareindexof element, but can normally getindexof element in that situation using Array#index method.Correct approach:
You can parse
pathwithoutdrop_while.My solution:
It will cut out
["comments"]or["comments","2"]for your path.Invoke that method: