0

I have my third-party credentials set in the config/application.rb like a key, UUID, and other values.

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.UUID

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.config."#{v}"

2 Answers 2

2

Another way you may want to approach your problem is by storing your related config in a 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. You can add your related information under a key in the credentials file and get the advantages above while also keeping your data safe.

Sign up to request clarification or add additional context in comments.

Comments

1

Where no other mechanism exists, you can use Object#send or Object#public_send to call a dynamic method name. 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. I don't see an obvious one in this case.

1 Comment

Thanks, @matthew_tuck for the quick response. For now, I will go the dynamic method then.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.