how to get at config variables from a plugin
hi, new to Ruby.
In my configuration.yml I have
how would I get at these from a plugin? I tried Rails.application.config.email_delivery.smtp_settings.address but it didn't work.
RE: how to get at config variables from a plugin - Added by Liane Hampe 11 months ago
As you can see from the file ending, the configuration.yml is a YAML file. That means, the file has to be read to get its values. There are two possiblities to get the files content for your plugin:
- You search the Redmine or Rails code for configuration.yml to find the variable where the files data are stored in and use this variable.
- You read the file by yourself.
When choosing the second possibility, I can show you three approaches:
configuration = YAML.load_file(File.join(Rails.root, 'config', 'configuration.yml')
The above code will give you a Ruby Hash with keys as String. You can use it like so:
configuration['email_delivery']['delivery_method'} # => "smtp"
When you prefer Symbols as key, then use:
configuration = JSON.parse(JSON.dump(YAML.load_file(File.join(Rails.root, 'config', 'configuration.yml')),symbolize_names: true)
This will let you write:
configuration[:email_delivery][:delivery_method} # => "smtp"
Method chaining, as you tried, is also possible with a single line of code:
configuration = JSON.parse(JSON.dump(YAML.load_file(File.join(Rails.root, 'config', 'configuration.yml')),object_class: OpenStruct)
Then you can write:
configuration.email_delivery.delivery_method # => "smtp"
You can find a lot of Ruby Modules and the like on https://ruby-doc.org/. Especially, the Hash and OpenStruct Module may be of interesst for you.
BTW, probabliy you need require YAML, JSON, and OpenStruct Modules in the file where you use the code above:
# Write above your class or module if you get an error require 'json' require 'ymal' require 'ostruct'
thanks but I was able to get at it like this, only took me 2 days to find it :-)
FWIW: I've added a paragraph on this to the Plugin FAQ with a reference back to this thread.