Module: OptionsHash::ClassMethods

Defined in:
lib/options_hash.rb

Instance Method Summary collapse

Instance Method Details

#[](key) ⇒ Object



58
59
60
61
# File 'lib/options_hash.rb', line 58

def [] key
  option? key or raise KeyError, "#{key} is not an option", caller(1)
  options[key]
end

#class_nameObject



98
99
100
# File 'lib/options_hash.rb', line 98

def class_name
  name || "OptionsHash:#{_inspect[/^#<Class:(\w+)/,1]}"
end

#define_attr_readers(object, instance_variable_name = :@options) ⇒ Object



85
86
87
88
89
90
91
92
93
# File 'lib/options_hash.rb', line 85

def define_attr_readers object, instance_variable_name=:@options
  self.freeze
  instance_variable_name = "@#{instance_variable_name.to_s.sub(/@/,'')}"
  keys.each do |key|
    object.send(:define_method, "#{key}" ) do
      instance_variable_get(instance_variable_name)[key]
    end
  end
end

#inspectObject Also known as: to_s



102
103
104
105
106
107
# File 'lib/options_hash.rb', line 102

def inspect
  inspect = super
  required_keys = self.required_keys.to_a.sort
  optional_keys = self.optional_keys.to_a.sort
  "#{class_name}(required: #{required_keys.inspect}, optional: #{optional_keys.inspect})"
end

#keysObject



63
64
65
# File 'lib/options_hash.rb', line 63

def keys
  options.keys.to_set
end

#option?(key) ⇒ Boolean

Returns:

  • (Boolean)


54
55
56
# File 'lib/options_hash.rb', line 54

def option? key
  keys.include? key
end

#optional(*options, &block) ⇒ Object



80
81
82
83
# File 'lib/options_hash.rb', line 80

def optional *options, &block
  default = extract_default options, &block
  set_options Option.new(false, default), *options
end

#optional_keysObject



71
72
73
# File 'lib/options_hash.rb', line 71

def optional_keys
  options.reject{|key, option| option.required? }.keys.to_set
end

#optionsObject



49
50
51
52
# File 'lib/options_hash.rb', line 49

def options
  @options ||= {}
  (superclass.respond_to?(:options) ? superclass.options : {}).merge @options
end

#parse(options) ⇒ Object



43
44
45
46
47
# File 'lib/options_hash.rb', line 43

def parse options
  _new options
rescue ArgumentError => error
  raise ArgumentError, error.message, caller(2)
end

#required(*options, &block) ⇒ Object



75
76
77
78
# File 'lib/options_hash.rb', line 75

def required *options, &block
  default = extract_default options, &block
  set_options Option.new(true, default), *options
end

#required_keysObject



67
68
69
# File 'lib/options_hash.rb', line 67

def required_keys
  options.select{|key, option| option.required? }.keys.to_set
end