Simple configuration files usually looks like:
foo:bar
zed:set
baz:foo1
It all placed comfortably into OpenStruct
, that are made for this kind of thing.
Implementation
require "ostruct"
config = OpenStruct.new(
File.read("config.conf") # read the file
.each_line
.map(&:strip)
.reject(&:empty?) # remove the empty lines
.map(&->(str){str.split(":") }) # split the lines
.reduce(Hash.new){ |hash, arr|
hash.merge!({arr.first => arr.last}) # place into hash
}
)
# voila
p config #=> #<OpenStruct foo="bar", zed="set", baz="foo1">
Simple and easy.
Extra
When we want to make sure that the method is really defined, for example:
config.foo? # => true or false
Then we need to add a module in the OpenStruct
:
module OStructExtra
if method.to_s.end_with?("?")
method = method[0...-1].to_sym
!!marshal_dump[method] # cast to the bool
else
marshal_dump[method]
end
end
# and then
config = OpenStruct.new(
# ...
).extend(OStructExtra)
p config.foo? #=> true
p config.foo0? #=> false