[英]How to access the Rails application configuration data with string interpolation
I have my third-party credentials set in the config/application.rb like a key, UUID, and other values.我在 config/application.rb 中设置了我的第三方凭据,例如密钥、UUID 和其他值。
config.username = "username"
config.uuid = "uuid"
config.yyy = "yyy"
For fetching them, I have to write multiple lines to fetch the data which is为了获取它们,我必须编写多行来获取数据
Rails.application.config.key Rails.application.config.key
Rails.application.config.UUID Rails.application.config.UUID
Rails.application.config.yyy Rails.application.config.yyy
Instead of using the above, I have defined an array with a set of elements loop through it, and get the config value.我没有使用上面的方法,而是定义了一个数组,其中包含一组循环遍历它的元素,并获取配置值。 But I am not able to get the config value, since fetching through a variable is not allowing.但我无法获取配置值,因为不允许通过变量获取。 Let me know if any alternative让我知道是否有其他选择
arr = ["key", "uuid", "vv"]
arr.each do |v|
# Fetching the config value from application config
Rails.application.config.v
# Or
Rails.application.config."#{v}"
end
Getting an error saying - undefined method `v' for #Rails::Application::Configuration:0x0000000152e4f360 (or) SyntaxError ((irb):1919: syntax error, unexpected tSTRING_BEG)...ass;收到错误消息 - #Rails::Application::Configuration:0x0000000152e4f360 的未定义方法“v” (或) SyntaxError((irb):1919:语法错误,意外的tSTRING_BEG)...ass; Rails.application.config."#{v}" Rails.application.config."#{v}"
Another way you may want to approach your problem is by storing your related config in a hash:您可能想要解决问题的另一种方法是将相关配置存储在 hash 中:
config.third_party_stuff = {
username: 'username',
uuid: 'uuid',
yyy: 'yyy'
}
Then you can do can pull it out all together:然后你可以把它全部拉出来:
third_party_config = Rails.application.config.third_party_stuff
puts "Hey #{third_party_config[:username]}, your uuid is #{third_party_config[:uuid]}"
If you are storing sensitive information, take a look at rails credentials .如果您要存储敏感信息,请查看rails credentials 。 You can add your related information under a key in the credentials file and get the advantages above while also keeping your data safe.您可以在凭证文件中的密钥下添加相关信息,并在获得上述优势的同时保证数据安全。
Where no other mechanism exists, you can use Object#send
or Object#public_send
to call a dynamic method name.在不存在其他机制的情况下,您可以使用Object#send
或Object#public_send
来调用动态方法名称。 For example:例如:
Rails.configuration.public_send(v)
If another mechanism exists, like square bracket notation, slice
method, or obtaining or converting to a hash, that may be considered preferable.如果存在另一种机制,例如方括号表示法、 slice
方法,或者获取或转换为 hash,则可能被认为是更可取的。 I don't see an obvious one in this case.在这种情况下,我看不到一个明显的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.