【问题标题】:Rails style routing string parsing using Journey only仅使用 Journey 的 Rails 样式路由字符串解析
【发布时间】:2013-02-22 02:58:33
【问题描述】:

鉴于此映射定义: /order/:meal/:cheese

将此字符串/order/hamburger/american 解析为{meal:'hamburger', cheese:'american'}

我正在玩弄 Journey 的内部结构,试图弄清楚这在 Rails 之外是否可行。还有其他 SO 问题展示了如何在 Rails 中使用识别路径。而且我知道您可以使用正则表达式或拆分轻松完成此操作,但我想要免费的额外解析功能(例如 :format 等)。

这是可行的。只是想知道是否有人有改进。我基本上是在压缩/组合旅程匹配的两个部分(名称和捕获)以制作匹配哈希(如识别路径)。只是想知道是否有人已经进入 Journey 并尝试做同样的事情。

require 'journey'

def hashify_match matches
  h = {}
  matches.names.each_with_index do |key, i|
    h[key.to_sym] = matches.captures[i]
  end
  h
end

pattern = Journey::Path::Pattern.new '/order/(:meal(/:cheese))'
matches = pattern.match '/order/hamburger/american'

puts hashify_match matches

matches = pattern.match '/order/hotdog/cheddar'
puts hashify_match matches

这是打印出来的内容。

{:meal=>"hamburger", :cheese=>"american"}
{:meal=>"hotdog", :cheese=>"cheddar"}

我可以使用 Journey 的另一部分来构建匹配哈希吗?看,matches.namesmatches.captures 真的是 Array 对象,这感觉就像一个 hack。当然,Rails 的某些部分在某个时候将这些组合在一起。

请注意,仅使用 Journey gem(包含在 Rails 3.2.0+ 中)。

【问题讨论】:

    标签: ruby-on-rails ruby journey


    【解决方案1】:

    Journey::Router does it here:

        match_data  = r.path.match(req.path_info)
        match_names = match_data.names.map { |n| n.to_sym }
        match_values = match_data.captures.map { |v| v && Utils.unescape_uri(v) }
        info = Hash[match_names.zip(match_values).find_all { |_,y| y }]
    

    所以看起来好像没有一种方便的方法来做你想做的事情。

    【讨论】:

    • 是的,我猜不是。谢谢。
    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-06
    • 2013-08-25
    • 1970-01-01
    • 2015-06-30
    • 1970-01-01
    相关资源
    最近更新 更多