Class: HashWalker::Walker

Inherits:
Object
  • Object
show all
Defined in:
lib/hash_walker/walker.rb

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Walker



4
5
6
7
8
# File 'lib/hash_walker/walker.rb', line 4

def initialize(options)
  @hash_fragment = options[:hash]
  @hash_fragment = @hash_fragment.with_indifferent_access if @hash_fragment.is_a? Hash
  @block = options[:block]
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(*args, &block) ⇒ Object



33
34
35
36
37
38
# File 'lib/hash_walker/walker.rb', line 33

def method_missing(*args,&block)
  @attribute_name = args[0]
  @block = block

  take_one_step
end

Instance Method Details

#get_stepperObject



22
23
24
# File 'lib/hash_walker/walker.rb', line 22

def get_stepper
  next_step_is_array? ? Stepper::Array : Stepper::Hash
end

#next_step_is_array?Boolean



18
19
20
# File 'lib/hash_walker/walker.rb', line 18

def next_step_is_array?
  (@hash_fragment.is_a?(Hash) && value.is_a?(Array))
end

#take_one_stepObject



26
27
28
29
30
31
# File 'lib/hash_walker/walker.rb', line 26

def take_one_step
  stepper = get_stepper.new
  stepper.hash_fragment = value
  stepper.block = @block
  stepper.step!
end

#valueObject



14
15
16
# File 'lib/hash_walker/walker.rb', line 14

def value
  @hash_fragment.respond_to?('keys') && @hash_fragment[@attribute_name]
end

#walk!Object



10
11
12
# File 'lib/hash_walker/walker.rb', line 10

def walk!
  instance_eval(&@block)
end