Module: OptionsHash::InstanceMethods

Defined in:
lib/options_hash.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#given_optionsObject (readonly)

Returns the value of attribute given_options.



145
146
147
# File 'lib/options_hash.rb', line 145

def given_options
  @given_options
end

#keysObject (readonly)

Returns the value of attribute keys.



145
146
147
# File 'lib/options_hash.rb', line 145

def keys
  @keys
end

#optionsObject (readonly)

Returns the value of attribute options.



145
146
147
# File 'lib/options_hash.rb', line 145

def options
  @options
end

Instance Method Details

#fetch(key) ⇒ Object Also known as: []



157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
# 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

#given?(key) ⇒ Boolean

Returns:

  • (Boolean)


153
154
155
# File 'lib/options_hash.rb', line 153

def given? key
  @given_options.key? key
end

#initialize(given_options) ⇒ Object



130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
# 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

#inspectObject Also known as: to_s



183
184
185
# File 'lib/options_hash.rb', line 183

def inspect
  %(#<#{self.class.class_name} #{to_hash.inspect}>)
end

#required_keysObject



147
148
149
150
151
# File 'lib/options_hash.rb', line 147

def required_keys
  @options.select do |key, option|
    option.required?
  end.keys.to_set
end

#to_hashObject



176
177
178
179
180
# 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