Module: OptionsHash::InstanceMethods
- Defined in:
- lib/options_hash.rb
Instance Attribute Summary collapse
-
#given_options ⇒ Object
readonly
Returns the value of attribute given_options.
-
#keys ⇒ Object
readonly
Returns the value of attribute keys.
-
#options ⇒ Object
readonly
Returns the value of attribute options.
Instance Method Summary collapse
- #fetch(key) ⇒ Object (also: #[])
- #given?(key) ⇒ Boolean
- #initialize(given_options) ⇒ Object
- #inspect ⇒ Object (also: #to_s)
- #required_keys ⇒ Object
- #to_hash ⇒ Object
Instance Attribute Details
#given_options ⇒ Object (readonly)
Returns the value of attribute given_options.
145 146 147 |
# File 'lib/options_hash.rb', line 145 def @given_options end |
#keys ⇒ Object (readonly)
Returns the value of attribute keys.
145 146 147 |
# File 'lib/options_hash.rb', line 145 def keys @keys end |
#options ⇒ Object (readonly)
Returns the value of attribute options.
145 146 147 |
# File 'lib/options_hash.rb', line 145 def @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
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 @keys = self.class.keys.freeze @options = self.class..freeze @given_options = ( || {}).freeze = @given_options.keys - keys.to_a .empty? or raise ArgumentError, "unknown options: #{.sort.map(&:inspect).join(', ')}" = required_keys.to_a - @given_options.keys .empty? or raise ArgumentError, "required options: #{.sort.map(&:inspect).join(', ')}" @values = {} keys.to_a.sort.each{|key| send(key) } end |
#inspect ⇒ Object 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_keys ⇒ Object
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_hash ⇒ Object
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 |