default.rb 872 B

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. require "digest/md5"
  2. module RailsSettings
  3. class Default < ::Hash
  4. class MissingKey < StandardError; end
  5. class << self
  6. def enabled?
  7. source_path && File.exist?(source_path)
  8. end
  9. def source(value = nil)
  10. @source ||= value
  11. end
  12. def source_path
  13. @source || Rails.root.join("config/app.yml")
  14. end
  15. def [](key)
  16. # foo.bar.dar Nested fetch value
  17. return instance[key] if instance.key?(key)
  18. keys = key.to_s.split(".")
  19. instance.dig(*keys)
  20. end
  21. def instance
  22. return @instance if defined? @instance
  23. @instance = new
  24. end
  25. end
  26. def initialize
  27. content = open(self.class.source_path).read
  28. hash = content.empty? ? {} : YAML.load(ERB.new(content).result).to_hash
  29. hash = hash[Rails.env] || {}
  30. replace hash
  31. end
  32. end
  33. end