URL 参数包括用破折号分隔的破折号

问题描述 投票:0回答:1

使用由破折号分隔的虚线段的最佳方法:

get ':foo-:bar', to: 'foo#bar' 

foo
可以是
my-value
并且
bar
可以是
other-value

我的网址是

my-value-other-value

除了将参数分隔符更改为其他内容之外,最好的方法是什么?

我确实知道 foo 的所有值和 bar 的所有值,因为它们存储在相应的模型中。我担心使用这种方法性能会很差。

ruby-on-rails
1个回答
0
投票

以下正则表达式将提取您要查找的 slug 值:

my_value = ["big-deal","hoi-polloi","nodash"]
other_value = ["east-coast","chumbawumba","abba-zabba"]
regex = /^(#{my_value.join("|")})?-(#{other_value.join("|")})?/

test_strings = ["big-deal-wtf", "nodash-chumbawumba","nodash-abba-zabba","hoi-polloi-east-coast"]

test_strings.each {|string| match = string.match(regex); puts [match && match[1],match && match[2]].inspect}

结果匹配是:

["big-deal", nil]
["nodash", "chumbawumba"]
["nodash", "abba-zabba"]
["hoi-polloi", "east-coast"]

满足您的需求吗?

© www.soinside.com 2019 - 2024. All rights reserved.