Module: Interface

Defined in:
lib/interface_semantics.rb

Constant Summary collapse

DoesNotImplementError =
Class.new(StandardError)
IncorrectReturnType =
Class.new(StandardError)
IncorrectArgumentsError =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.for_messages(&block) ⇒ Object



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/interface_semantics.rb', line 18

def self.for_messages(&block)
  attributes = DSL.run(&block)

  Module.new do
    attributes_string = attributes.map { |a| "Attribute.new(:#{a.name}, #{a.argument_types}, #{a.return_type})" }.join(",")
    init = "      def initialize(*)\n        @__attributes = [\#{attributes_string}]\n        super\n        after_initialize\n      end\n    RUBY\n\n    attributes.each do |a|\n      argument_checks = a.argument_types.each_with_index.map do |at, i|\n        \"raise IncorrectArgumentsError unless args[\#{i}].class == \#{at.name};\"\n      end.join(\" \")\n\n      method_wrapper = \"def \#{a.name}(*args); \#{argument_checks} super.tap do |return_val| raise IncorrectReturnType unless return_val.class == \#{a.return_type}; end; end\"\n\n      module_eval(method_wrapper)\n    end\n\n    module_eval(init)\n\n    module_eval(\"def run_checks; \" + attributes.map { |a| \"raise DoesNotImplementError, :\#{a.name} if self.method(:\#{a.name}).super_method.nil?;\" }.join(\"\") + \"end\")\n\n    def after_initialize\n      run_checks\n    end\n  end\nend\n"