module OptionsHash::ClassMethods
Public Instance Methods
[](key)
click to toggle source
# 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_name()
click to toggle source
# 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)
click to toggle source
# 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
inspect()
click to toggle source
Calls superclass method
# 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
keys()
click to toggle source
# File lib/options_hash.rb, line 63 def keys options.keys.to_set end
option?(key)
click to toggle source
# File lib/options_hash.rb, line 54 def option? key keys.include? key end
optional(*options, &block)
click to toggle source
# 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_keys()
click to toggle source
# File lib/options_hash.rb, line 71 def optional_keys options.reject{|key, option| option.required? }.keys.to_set end
options()
click to toggle source
# File lib/options_hash.rb, line 49 def options @options ||= {} (superclass.respond_to?(:options) ? superclass.options : {}).merge @options end
parse(options)
click to toggle source
# 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)
click to toggle source
# 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_keys()
click to toggle source
# File lib/options_hash.rb, line 67 def required_keys options.select{|key, option| option.required? }.keys.to_set end
Private Instance Methods
extract_default(options, &block)
click to toggle source
# File lib/options_hash.rb, line 112 def extract_default options, &block return block if block_given? (options.last.is_a?(Hash) ? options.pop : {})[:default] end
set_options(definition, *options)
click to toggle source
# File lib/options_hash.rb, line 117 def set_options definition, *options @options ||= {} options.each do |key| key = key.to_sym @options[key] = definition.dup define_method("#{key}" ){ fetch key } define_method("#{key}?"){ given? key } end end