Module: AutoMock::AutoMockHelper

Defined in:
lib/auto_mock/auto_mock_helper.rb

Instance Method Summary collapse

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/auto_mock/auto_mock_helper.rb', line 3

def method_missing(name, *args)
  if matched = name.to_s.match(/mock_(.*)/)
    klass = matched[1].classify.constantize
    multi_name = "mock_#{klass.name.tableize}".to_sym

    array_name = "@#{multi_name.to_s}"
    self.class.send(:define_method, multi_name) do |key, stubs|
      stubs = stubs.try(:first) || {}
      array = instance_variable_get(array_name) || {}
      if array.has_key?(key)
        return array[key]
      end
      array[key] = mock_model(klass, stubs).as_null_object
      instance_variable_set(array_name, array)
      array[key]
    end

    single_name = "mock_#{klass.name.tableize.singularize}".to_sym
    self.class.send(:define_method, single_name) do |*stubs|
      send(multi_name, :default, stubs)
    end

    send(name, *args)
  else
    super
  end
end