Last Updated: February 25, 2016
·
798
· zunda

Reading user configuration file on Ruby

class Configuration
    attr_reader :_error_
    attr_reader :auth

    def _error_=(error)
        @_error_ = error
    end

    def ConfigurationBase.load(path)
        c = self.new()
        begin
            c.instance_eval(File.read(File.expand_path(path)))
        rescue SystemCallError => e
            c._error_ = e
        end
        return c
    end
end

conf = Configuration.load('~/.auth')
if conf._error_
    $stderr.puts "Warning: #{conf._error_.message}"
end

puts conf.auth  #=> ['username', 'password']

Reference: http://jp.rubyist.net/magazine/?0015-CodeReview#l41