0

我正在尝试解析 URL。例如,我试图退出的地方:

~/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 似乎不起作用。

4

1 回答 1

1

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

已编辑

你的问题是你转换元素to_i,它是0. 但是您想比较index元素,但通常可以index使用Array#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"] 
于 2012-05-27T09:20:28.287 回答