English 中文(简体)
分析 URL 并删除结束部分
原标题:Parse a URL and remove end portion

我试图解析 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 中手动键入。 拖放似乎不起作用 。

最佳回答

处理密码后你有什么输出?

Edited

您的问题是您转换了元素 to_ i < /code>, 它是 0 < /code> 。 但是您想要比较元素的 index , 但通常使用 < a href=> http://www.ruby-doc.org/core-1.9.3/Array.html#method- i- index" rel="nofolt noreferrerr" 。 您想要比较元素的 index , 但通常可以使用 < a href=" 方法获得元素的 index

<强度 > 更正方法:

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

您可以在不使用 drop_而使用 的情况下分析 path

<强> 我的解决方案:

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"] 
问题回答

暂无回答




相关问题
Remove ActiveRecord in Rails 3

Now that Rails 3 beta is out, I thought I d have a look at rewriting an app I have just started work on in Rails 3 beta, both to get a feel for it and get a bit of a head-start. The app uses MongoDB ...

When will you upgrade your app to Rails 3? [closed]

Now that the Rails 3 beta is here, let s take a little straw poll. Please tell us briefly what your application does and when you will upgrade it to Rails 3. Or, if you re not planning on upgrading ...

Bundler isn t loading gems

I have been having a problem with using Bundler and being able to access my gems without having to require them somewhere, as config.gem used to do that for me (as far as I know). In my Rails 3 app, I ...

bypass attr_accessible/protected in rails

I have a model that, when it instantiates an object, also creates another object with the same user id. class Foo > ActiveRecord::Base after_create: create_bar private def create_bar Bar....

concat two fields activerecord

I m so used to oracle where you can simply concat(field1, , field2) but if I m using activerecord to find the field1 and field2, and I need a space in between, how do I accomplish this? Cheers ...