how to get at config variables from a plugin

Added by Alex Liberman about 1 month ago

hi, new to Ruby.

In my configuration.yml I have

email_delivery:
delivery_method: :smtp
smtp_settings:
address: "myaddress.com"
port: 25
domain: "mydomain.com"

how would I get at these from a plugin? I tried Rails.application.config.email_delivery.smtp_settings.address but it didn't work.

Replies (4)

RE: how to get at config variables from a plugin - Added by Liane Hampe about 1 month ago

Hi Alex,

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:

  1. 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.
  2. 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'

Best Regards,
Liane

RE: how to get at config variables from a plugin - Added by Alex Liberman about 1 month ago

thanks but I was able to get at it like this, only took me 2 days to find it :-)

Redmine::Configuration['email_delivery']['smtp_settings'][:address]

RE: how to get at config variables from a plugin - Added by Mischa The Evil about 1 month ago

FWIW: I've added a paragraph on this to the Plugin FAQ with a reference back to this thread.

(1-4/4)