Class: TableSync::Utils::InterfaceChecker

Inherits:
Object
  • Object
show all
Defined in:
lib/table_sync/utils/interface_checker.rb

Overview

Ruby does not support interfaces, and there is no way to implement them. Interfaces check a methods of a class after the initialization of the class is complete. But in Ruby, the initialization of a class cannot be completed. In execution time we can open any class and add some methods (monkey patching). Ruby has ‘define_method`, singleton methods, etc.

Duck typing is a necessary measure, the only one available in the Ruby architecture.

Interfaces can be implemented in particular cases with tests for example. But this is not suitable for gems that are used by third-party code.

So, we still want to check interfaces and have a nice error messages, even if it will be duck typing.

Next code do this.

Constant Summary collapse

INTERFACES =
SelfData.load

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(object) ⇒ InterfaceChecker

Returns a new instance of InterfaceChecker.



24
25
26
# File 'lib/table_sync/utils/interface_checker.rb', line 24

def initialize(object)
  @object = object
end

Instance Attribute Details

#objectObject (readonly)

Returns the value of attribute object.



22
23
24
# File 'lib/table_sync/utils/interface_checker.rb', line 22

def object
  @object
end

Instance Method Details

#implements(interface_name) ⇒ Object



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/table_sync/utils/interface_checker.rb', line 28

def implements(interface_name)
  INTERFACES[interface_name].each do |method_name, options|
    unless object.respond_to?(method_name)
      raise_error(method_name, options)
    end

    unless include?(object.method(method_name).parameters, options[:parameters])
      raise_error(method_name, options)
    end
  end
  self
end