Sha256: 53dfa81883e2150ddcee61660a2cd1158f820874ffb7d73d979618f02537963a

Contents?: true

Size: 1.51 KB

Versions: 4

Compression:

Stored size: 1.51 KB

Contents

# encoding: utf-8

module Pio
  # User options utility.
  class Options
    def self.mandatory_option(name)
      unless const_defined?(:MANDATORY_OPTIONS)
        const_set(:MANDATORY_OPTIONS, [])
      end
      const_get(:MANDATORY_OPTIONS) << name
    end

    def self.option(name)
      const_set(:OPTIONS, []) unless const_defined?(:OPTIONS)
      const_get(:OPTIONS) << name
    end

    private

    def validate(user_options)
      check_unknown user_options
      check_mandatory user_options
    end

    def mandatory_options
      klass = self.class
      if klass.const_defined?(:MANDATORY_OPTIONS)
        klass.const_get(:MANDATORY_OPTIONS)
      else
        []
      end
    end

    def options
      klass = self.class
      if klass.const_defined?(:OPTIONS)
        klass.const_get(:OPTIONS)
      else
        []
      end
    end

    def check_unknown(user_options)
      valid_options = mandatory_options + options
      user_options.keys.each do |each|
        fail "Unknown option: #{each}." unless valid_options.include?(each)
      end
    end

    def check_mandatory(user_options)
      self.class.const_get(:MANDATORY_OPTIONS).each do |each|
        check_existence(user_options, each)
      end
    end

    def check_existence(user_options, key)
      value = user_options.fetch(key) do |missing_key|
        fail ArgumentError, "The #{missing_key} option should be passed."
      end
      unless value
        fail(ArgumentError, "The #{key} option shouldn't be #{value.inspect}.")
      end
    end
  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
pio-0.7.0 lib/pio/options.rb
pio-0.6.0 lib/pio/options.rb
pio-0.5.0 lib/pio/options.rb
pio-0.4.0 lib/pio/options.rb