Sha256: 49824551a221a6a88558ecde108c1276a305e3e3696845d5e61dd5ac453d0c7e

Contents?: true

Size: 1.03 KB

Versions: 5

Compression:

Stored size: 1.03 KB

Contents

require 'active_support/core_ext/hash/indifferent_access'

module Pears 
  # A subject is a collection of settings.
  # You could different Pears::Subjects in your application for different parts
  # of its domain. for instance: application_settings, theming or translations.
  class Subject
    include Enumerable
    attr_reader :name

    def initialize(name, *layers)
      @name = name
      @layers = layers
      Pears.subjects << self
    end

    def [](key)
      project[key]
    end

    def keys
      project.keys
    end

    def has_key?(key)
      project.has_key? key
    end

    def dig(*args)
      project.dig(*args)
    end

    def push_layer(layer)
      @layers << layer
    end

    # Projects the layers to a hash that van be used as a single source of truth.
    def project
      layers.reverse.reduce(Hash.new) do |hash, layer|
        hash.deep_merge(layer.data)
      end.with_indifferent_access
    end

    def each(&block)
      project.each(&block)
    end

    private

    def layers
      @layers
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
pears-0.2.0 lib/pears/subject.rb
pears-0.1.4 lib/pears/subject.rb
pears-0.1.3 lib/pears/subject.rb
pears-0.1.2 lib/pears/subject.rb
pears-0.1.1 lib/pears/subject.rb