Class: Arcanus::Chest::Item

Inherits:
Object
  • Object
show all
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

Constructor Details

#initialize(hash, prefix) ⇒ Item

Returns a new instance of Item.


219
220
221
222
# File 'lib/arcanus/chest.rb', line 219

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, *args) ⇒ Object


246
247
248
249
250
251
252
253
# File 'lib/arcanus/chest.rb', line 246

def method_missing(method_sym, *args)
  method_name = method_sym.to_s
  if @hash.key?(method_name)
    self[method_name]
  else
    super
  end
end

Instance Method Details

#[](key) ⇒ Object

Access the item as if it were a hash.

This will raise an error if the key does not exist, however.

Parameters:

  • key (String)

Returns:

  • (Object)

230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
# File 'lib/arcanus/chest.rb', line 230

def [](key)
  if @hash.key?(key)
    value = @hash[key]
    if value.is_a?(Hash)
      Item.new(value, @prefix + [key])
    else
      value
    end
  else
    key_name = "#{@prefix.join('.')}.#{key}"
    raise KeyError,
          "Key '#{key_name}' does not exist in this Arcanus chest",
          caller
  end
end

#fetch(*args) ⇒ Object

Fetch key from the chest as if it were a hash.


264
265
266
# File 'lib/arcanus/chest.rb', line 264

def fetch(*args)
  @hash.fetch(*args)
end

#inspectObject


272
273
274
# File 'lib/arcanus/chest.rb', line 272

def inspect
  @hash.inspect
end

#respond_to?(method_sym) ⇒ Boolean

Returns:

  • (Boolean)

259
260
261
# File 'lib/arcanus/chest.rb', line 259

def respond_to?(method_sym, *)
  @hash.key?(method_sym.to_s) || super
end

#respond_to_missing?(method_name, *args) ⇒ Boolean

Returns:

  • (Boolean)

255
256
257
# File 'lib/arcanus/chest.rb', line 255

def respond_to_missing?(method_name, *args)
  @hash.key?(method_name.to_s) ? true : super
end

#to_aryObject

Implicit conversion to array. Needs to be defined so we can `puts` this value.


282
283
284
# File 'lib/arcanus/chest.rb', line 282

def to_ary
  [@hash]
end

#to_hashObject


276
277
278
# File 'lib/arcanus/chest.rb', line 276

def to_hash
  @hash.dup
end

#to_sObject


268
269
270
# File 'lib/arcanus/chest.rb', line 268

def to_s
  @hash.to_s
end