解析URL并删除结尾部分

时间:2012-05-27 07:23:24

标签: ruby-on-rails-3

我正在尝试解析网址。例如,我想拉出来的地方:

~/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]

格式非常一致。我从数组开始,但似乎仍然失败:

@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)

我添加了小写,只是在某人手动输入一个大写的URL中。 drop_while似乎无法正常工作。

1 个答案:

答案 0 :(得分:1)

处理代码后有什么样的输出?

被修改

您的问题是转换元素to_i并且它是0。但您希望比较index元素,但通常可以使用Array#index方法在该情况下获取index元素。

正确的方法:

@request_path.drop_while { |i| @request_path.index(i) >= @comment_index }

您可以在不path的情况下解析drop_while

我的解决方案:

def resource_details(path)
    resource_array = path.downcase.split("/").reject!(&:empty?)
    key = resource_array.index("comments")
    return key.present? ? (resource_array - resource_array[key..key + 1]).last(2) : resource_array.last(2)
 end

它将为您的路径删除["comments"]["comments","2"]

调用该方法:

1.9.3p0 :051 > resource_details("/locations/1/buildings/3/comments")
 => ["buildings", "3"] 

1.9.3p0 :052 > resource_details("/locations/1/comments/2")
 => ["locations", "1"]