lib/envied.rb in envied-0.4.0 vs lib/envied.rb in envied-0.5.0
- old
+ new
@@ -1,13 +1,27 @@
require 'virtus'
class ENVied
+ module Hashable
+ def to_hash
+ require 'rack/utils'
+ ::Rack::Utils.parse_nested_query(self)
+ end
+ end
+
+ module Arrayable
+ def to_a
+ self.split(/(?<!\\), ?/).map{|i| i.gsub(/\\,/,',') }
+ end
+ end
+
class Configuration
include Virtus.model
def self.variable(name, type = :String, options = {})
- options = { strict: true, group: self.current_group }.merge(options)
+ options = { default: nil, strict: true, group: self.current_group }.merge(options)
+ type = Array if type == :Array
attribute(name, type, options)
end
def self.group(name, &block)
self.current_group = name.to_sym
@@ -34,11 +48,11 @@
end
def self.configuration(options = {}, &block)
if block_given?
@configuration = build_configuration(&block).tap do |c|
- options.each{|k, v| c.public_send("#{k}=", v) }
+ options.each {|k, v| c.public_send("#{k}=", v) }
end
end
@configuration ||= build_configuration
end
@@ -68,20 +82,21 @@
group_configuration = build_configuration do
_required_variables.each do |v|
@attribute_set << v
end
end
- @instance = group_configuration.new(ENV.to_hash)
+ @instance = group_configuration.new(env)
end
def self.error_on_missing_variables!
if missing_variable_names.any?
raise "Please set the following ENV-variables: #{missing_variable_names.sort.join(',')}"
end
end
def self.error_on_uncoercible_variables!
+ # TODO default values should have defined type
if non_coercible_variables.any?
single_error = "ENV['%{name}'] ('%{value}' can't be coerced to %{type})"
errors = non_coercible_variables.map do |v|
var_type = v.type.to_s.split("::").last
single_error % { name: v.name, value: env_value_or_default(v), type: var_type }
@@ -90,10 +105,16 @@
raise "Some ENV-variables are not coercible: #{errors}"
end
end
def self.env_value(variable)
- ENV[variable.name.to_s]
+ env[variable.name.to_s]
+ end
+
+ def self.env
+ @env ||= begin
+ Hash[ENV.to_hash.map {|k,v| [k, v.dup.extend(Hashable, Arrayable)] }]
+ end
end
def self.env_value_or_default(variable)
env_value(variable) || default_value(variable)
end