module OptionsHash::InstanceMethods

Attributes

given_options[R]
keys[R]
options[R]

Public Class Methods

new(given_options) click to toggle source
# File lib/options_hash.rb, line 130
def initialize given_options
  @keys          = self.class.keys.freeze
  @options       = self.class.options.freeze
  @given_options = (given_options || {}).freeze

  unknown_options = @given_options.keys - keys.to_a
  unknown_options.empty? or raise ArgumentError, "unknown options: #{unknown_options.sort.map(&:inspect).join(', ')}"

  missing_required_options = required_keys.to_a - @given_options.keys
  missing_required_options.empty? or raise ArgumentError, "required options: #{missing_required_options.sort.map(&:inspect).join(', ')}"


  @values        = {}
  keys.to_a.sort.each{|key| send(key) }
end

Public Instance Methods

[](key)
Alias for: fetch
fetch(key) click to toggle source
# File lib/options_hash.rb, line 157
def fetch key
  key = key.to_sym
  keys.include?(key) or raise KeyError, "#{key} is not an option", caller(1)
  return @values[key] if @values.key? key

  option = @options[key]
  default_proc = option.default if option.default && option.default.is_a?(Proc)

  if option.required?
    value = @given_options[key]
    value = instance_exec(value, &default_proc) if option.required? && default_proc
    return @values[key] = value
  end

  return @values[key] = @given_options[key] if @given_options.key? key
  return @values[key] = default_proc ? instance_exec(&default_proc) : option.default
end
Also aliased as: []
given?(key) click to toggle source
# File lib/options_hash.rb, line 153
def given? key
  @given_options.key? key
end
inspect() click to toggle source
# File lib/options_hash.rb, line 183
def inspect
  %(#<#{self.class.class_name} #{to_hash.inspect}>)
end
Also aliased as: to_s
required_keys() click to toggle source
# File lib/options_hash.rb, line 147
def required_keys
  @options.select do |key, option|
    option.required?
  end.keys.to_set
end
to_hash() click to toggle source
# File lib/options_hash.rb, line 176
def to_hash
  keys.each_with_object Hash.new do |key, hash|
    hash[key] = send(key)
  end
end
to_s()
Alias for: inspect