[英]How to do string interpolation in rails config?
I am using the rails config gem to feed external urls into my application. 我正在使用rails config gem将外部URL馈入我的应用程序。 I would like to do parameter interpolation in the following manner:
我想通过以下方式进行参数插值:
settings.yml settings.yml
url: 'http://www.example.com/#{self.param}'
then in model.rb: 然后在model.rb中:
def get_path
magic(Settings.url) #some magic procedure or function here
end
When I call get path I would like to have the fully interpolated url. 当我打电话给get path时,我想拥有完整内插的url。 Is there some "magic" function or method that would allow me to do that with railsconfig ?
是否有一些“魔术”功能或方法可以使我使用railsconfig进行操作 ? I would prefer something safer than passing the string into an eval call.
与将字符串传递给eval调用相比,我更喜欢更安全的方法。
Assuming you want self.param
interpreted at runtime when get_path
is invoked, you could use ERB to parse the result. 假设你想
self.param
在运行时解释时get_path
被调用时,你可以使用ERB解析结果。 For example: 例如:
require 'erb'
def get_path(url, param)
bar = "1"
ERB.new(url).result(binding)
end
url = "http://www.example.com/<%= param %>?bar=<%= bar %>"
param = "foo"
puts get_path(url, param)
Would yield: 将产生:
http://www.example.com/foo?bar=1
I ended up using the following method: 我最终使用以下方法:
settings.yml: settings.yml:
url: 'http://www.example.com/%{param}'
model.rb: model.rb:
def get_path
Settings.url % {param: self.param}
end
which properly returns the current value of param interpolated into the string when model#get_path is called. 当调用model#get_path时,它会正确返回插值到字符串中的param的当前值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.