default.rb 1008 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  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. val = instance
  20. keys.each do |k|
  21. val = val.fetch(k.to_s, nil)
  22. break if val.nil?
  23. end
  24. val
  25. end
  26. def instance
  27. return @instance if defined? @instance
  28. @instance = new
  29. @instance
  30. end
  31. end
  32. def initialize
  33. content = open(self.class.source_path).read
  34. hash = content.empty? ? {} : YAML.unsafe_load(ERB.new(content).result).to_hash
  35. hash = hash[Rails.env] || {}
  36. replace hash
  37. end
  38. end
  39. end