[英]How to pass string interpolation code to Rails Application Template CODE block?
[英]How to access the Rails application configuration data with string interpolation
我在 config/application.rb 中設置了我的第三方憑據,例如密鑰、UUID 和其他值。
config.username = "username"
config.uuid = "uuid"
config.yyy = "yyy"
為了獲取它們,我必須編寫多行來獲取數據
Rails.application.config.key
Rails.application.config.UUID
Rails.application.config.yyy
我沒有使用上面的方法,而是定義了一個數組,其中包含一組循環遍歷它的元素,並獲取配置值。 但我無法獲取配置值,因為不允許通過變量獲取。 讓我知道是否有其他選擇
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
收到錯誤消息 - #Rails::Application::Configuration:0x0000000152e4f360 的未定義方法“v” (或) SyntaxError((irb):1919:語法錯誤,意外的tSTRING_BEG)...ass; Rails.application.config."#{v}"
您可能想要解決問題的另一種方法是將相關配置存儲在 hash 中:
config.third_party_stuff = {
username: 'username',
uuid: 'uuid',
yyy: 'yyy'
}
然后你可以把它全部拉出來:
third_party_config = Rails.application.config.third_party_stuff
puts "Hey #{third_party_config[:username]}, your uuid is #{third_party_config[:uuid]}"
如果您要存儲敏感信息,請查看rails credentials 。 您可以在憑證文件中的密鑰下添加相關信息,並在獲得上述優勢的同時保證數據安全。
在不存在其他機制的情況下,您可以使用Object#send
或Object#public_send
來調用動態方法名稱。 例如:
Rails.configuration.public_send(v)
如果存在另一種機制,例如方括號表示法、 slice
方法,或者獲取或轉換為 hash,則可能被認為是更可取的。 在這種情況下,我看不到一個明顯的問題。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.