Sha256: 0dbbb120f5bbab24dfc042a44311d096e78acdc82334356a9c0666916760064e

Contents?: true

Size: 1.6 KB

Versions: 7

Compression:

Stored size: 1.6 KB

Contents

require "ostruct"

module Getto
  module Roda
    class Config
      def self.configure(schema)
        c = Struct.new
        yield c
        c.freeze
        c.tap do
          Checker.new(schema).validate!(c)
        end
      end

      class Struct < OpenStruct
        def group(name)
          self[name] ||= Struct.new
          yield self[name]
        end

        def freeze
          each_pair.each do |_,value|
            value.freeze
          end
          super
        end
      end

      class Checker
        def initialize(schema)
          @schema = schema
        end

        def validate!(config)
          validate_config!([], @schema, config)
        end

        private

          def validate_config!(path, schema, config)
            unless config
              raise "#{path.join("/")} is nil"
            end

            schema.each do |key,spec|
              case spec
              when ::Class
                unless config[key].is_a?(spec)
                  raise "#{full_path(path,key)} is not a #{spec}"
                end
              when ::Array
                unless spec.include?(config[key])
                  raise  "#{full_path(path,key)} is not in [#{spec.join(",")}]"
                end
              when ::Hash
                validate_config!([*path,key], spec, config[key])
              else
                # :nocov:
                raise "invalid schema: #{full_path(path,key)} : #{spec}"
                # :nocov:
              end
            end
          end

          def full_path(path,key)
            [*path, key].join("/")
          end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
getto-roda-1.1.3 lib/getto/roda/config.rb
getto-roda-1.1.2 lib/getto/roda/config.rb
getto-roda-1.1.1 lib/getto/roda/config.rb
getto-roda-1.1.0 lib/getto/roda/config.rb
getto-roda-1.0.0 lib/getto/roda/config.rb
getto-roda-0.1.0 lib/getto/roda/config.rb
getto-roda-0.2.0 lib/getto/roda/config.rb