ruby-on-rails - 使用匹配方法匹配动态数据
问题描述
我试图在 match 方法的帮助下匹配动态路由,但它不起作用。
["payment", "portal", "animation"].each do |arg|
define_method("profile_#{arg}") do
self.path.match("/users/\d+/#{arg}")
end
end
因此,此代码 self.path.match("/users/\d+/#{arg}") 不适用于插值。
而如果我做类似下面的事情,那么它就可以工作。那么,有没有办法动态匹配数据
self.path.match('/users/\d+/payment')
self.path.match('/users/\d+/portal')
self.path.match('/users/\d+/animation')
解决方案
您可以在正则表达式文字本身内进行插值。
?> s = "payment"
=> "payment"
>> %r(/users/\d+/#{s})
=> /\/users\/\d+\/payment/
推荐阅读
- python - 将两个字符串放入一个键中,其余的放入文件中多行的值
- javascript - 为什么 React Native Navigation 监听器在第一次尝试时触发?
- python - 使用python查找图像中最暗的颜色
- elasticsearch - 如何为通过服务相互通信的 2 组 Statefulset 的 Pod 创建自签名证书
- scala - Scala Play - 如何在响应消失之前修改 Cookie 设置值?
- python - 如果它以0开头,我如何计算任何数字的长度?
- sql-server - 会计年度sql server
- javascript - 如何直接从 Html 表单付款
- javascript - 我正在尝试使用 unsplash api 从 unsplash 获取一些信息,但出现错误,有人可以告诉我我做错了什么吗?
- class - 颤振,达特。创建匿名类