Module: Interface

Defined in:
lib/interface.rb,
lib/interface/version.rb

Defined Under Namespace

Modules: Abstract, ClassMethods

Constant Summary collapse

UnknownInterface =
Class.new(StandardError)
VERSION =
"0.2.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



27
28
29
# File 'lib/interface.rb', line 27

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#as(interface) ⇒ Object

Raises:



65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
# File 'lib/interface.rb', line 65

def as(interface)
  raise UnknownInterface.new(interface) unless self.class.interfaces.include?(interface)
  cached_interface_class(interface) do
    Class.new do
      def initialize(target)
        @target = target
      end

      interface.instance_methods.select do |method|
        interface.instance_method(method.to_sym).owner == interface
      end.each do |method|
        define_method(method) do |*args, &block|
          @target.public_send(method, *args, &block)
        end
      end

      [:is_a?, :kind_of?, :instance_of?].each do |type_method|
        define_method(type_method) do |target, &block|
          return true if target == interface
          super
        end
      end

      define_singleton_method :name do
        interface.name
      end

      define_singleton_method :inspect do
        name
      end

      define_method(:inspect) do
        "#<#{interface.name}:#{self.object_id}>"
      end
    end
  end.new(self)
end

#cached_interface_class(interface) ⇒ Object



56
57
58
59
60
61
62
# File 'lib/interface.rb', line 56

def cached_interface_class(interface)
  interface.instance_variable_get("@__cached_class__") || begin
    klass = yield
    interface.instance_variable_set("@__cached_class__", klass)
    klass
  end
end