S
S
Sergey Blokhin2016-09-01 13:43:50
ruby
Sergey Blokhin, 2016-09-01 13:43:50

What is the best way to work with configurations in Ruby?

Let's say we have some configuration structure (taken from YAML, JSON, XML, or simply as a Hash):

configuration = {
  gmail: {
    username: '[email protected]',
    password: 'pa$$word',
    host: 'imap.gmail.com',
    ssl: true,
    port: 993
  },
  ftp: {
    username: '[email protected]',
    password: 'pa$$word',
    host: 'imap.gmail.com',
    ssl: true,
    port: 42
  }
}

Further, based on this structure, we extract data from it:

mail = Mail.new host: configuration[:gmail][:host], port: configuration[:gmail][:port], username: configuration[:gmail][:username], password: configuration[:gmail][:password], ssl: configuration[:gmail][:ssl]
ftp = FTP.new host: configuration[:ftp][:host], port: configuration[:ftp][:port], username: configuration[:ftp][:username], password: configuration[:ftp][:password], ssl: configuration[:ftp][:ssl]

Everything works, but the code itself turns out to be poorly readable.
That is, it is, of course, understandable, but there is too much “dry” text, instead of the usual code for a programming language.
Share Best Practice on how to properly make and use configurations in Ruby.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
N. Bekseitov, 2016-09-01
@nbekseitov

Can be made easier

mail = Mail.new configuration[:gmail]
ftp = FTP.new configuration[:ftp]

K
kliss, 2016-09-08
@kliss

If you do not like access through brackets, then you can do this:

configuration = OpenStruct.new(configuration, object_class: OpenStruct)

configuration.gmail.host
configuration.ftp.port
# etc.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question