Class: Arcanus::Chest::Item
- Inherits:
-
Object
- Object
- Arcanus::Chest::Item
- Defined in:
- lib/arcanus/chest.rb
Overview
Helper class for returning contents nested hashes, exposing helpers to access them via method calls.
Instance Method Summary collapse
-
#[](key) ⇒ Object
Access the item as if it were a hash.
-
#fetch(*args) ⇒ Object
Fetch key from the chest as if it were a hash.
-
#initialize(hash, prefix = []) ⇒ Item
constructor
A new instance of Item.
- #inspect ⇒ Object
- #method_missing(method_sym) ⇒ Object
-
#to_ary ⇒ Object
Implicit conversion to array.
- #to_s ⇒ Object
Constructor Details
#initialize(hash, prefix = []) ⇒ Item
Returns a new instance of Item.
188 189 190 191 |
# File 'lib/arcanus/chest.rb', line 188 def initialize(hash, prefix = []) @hash = hash @prefix = prefix end |
Dynamic Method Handling
This class handles dynamic methods through the method_missing method
#method_missing(method_sym) ⇒ Object
193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 |
# File 'lib/arcanus/chest.rb', line 193 def method_missing(method_sym, *) method_name = method_sym.to_s if @hash.key?(method_name) value = @hash[method_name] if value.is_a?(Hash) Item.new(value, @prefix + [method_name]) else value end else key_name = "#{@prefix.join('.')}.#{method_name}" raise KeyError, "Key '#{key_name}' does not exist in this Arcanus chest", caller end end |
Instance Method Details
#[](key) ⇒ Object
Access the item as if it were a hash.
214 215 216 |
# File 'lib/arcanus/chest.rb', line 214 def [](key) @hash[key] end |
#fetch(*args) ⇒ Object
Fetch key from the chest as if it were a hash.
219 220 221 |
# File 'lib/arcanus/chest.rb', line 219 def fetch(*args) @hash.fetch(*args) end |
#inspect ⇒ Object
227 228 229 |
# File 'lib/arcanus/chest.rb', line 227 def inspect @hash.inspect end |
#to_ary ⇒ Object
Implicit conversion to array. Needs to be defined so we can ‘puts` this value.
233 234 235 |
# File 'lib/arcanus/chest.rb', line 233 def to_ary [@hash] end |
#to_s ⇒ Object
223 224 225 |
# File 'lib/arcanus/chest.rb', line 223 def to_s @hash.to_s end |