Class: Kindah::Compiler

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Defined in:
lib/kindah/compiler.rb

Instance Method Summary collapse

Constructor Details

#initialize(ast) ⇒ Compiler

Returns a new instance of Compiler.



5
6
7
# File 'lib/kindah/compiler.rb', line 5

def initialize(ast)
  @ast = ast
end

Instance Method Details

#class_methodsObject



9
10
11
# File 'lib/kindah/compiler.rb', line 9

def class_methods
  safe_fetch ClassMethods
end

#class_nameObject



22
23
24
# File 'lib/kindah/compiler.rb', line 22

def class_name
  @ast.name
end

#compile!(location = Object) ⇒ Object



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/kindah/compiler.rb', line 32

def compile!(location = Object)
  compiler = self # this trick carries the outer scope past ruby's stupid block-scoping rules.

  method_type = location == Object ? :define_method : :define_singleton_method

  location.send(method_type, compiler.class_name) do |*args|
    Kindah::Cache[compiler.class_name, *args] ||= compiler.create_klass_with_args *args
  end

  nil
end

#create_klass_with_args(*args) ⇒ Object



44
45
46
47
48
49
50
51
52
# File 'lib/kindah/compiler.rb', line 44

def create_klass_with_args(*args)
  compiler = self # this trick carries the outer scope past ruby's stupid block-scoping rules.

  Class.new(compiler.superklass) do
    compiler.install_template_arg_methods(self, *args)
    compiler.install_class_methods(self)
    compiler.install_instance_methods(self)
  end
end

#each_parameterObject



26
27
28
29
30
# File 'lib/kindah/compiler.rb', line 26

def each_parameter
  class_methods.parameters.each.with_index do |(_, name), idx|
    yield name, idx if block_given?
  end
end

#install_class_methods(target) ⇒ Object



61
62
63
# File 'lib/kindah/compiler.rb', line 61

def install_class_methods(target)
  target.instance_eval &class_methods
end

#install_instance_methods(target) ⇒ Object



65
66
67
# File 'lib/kindah/compiler.rb', line 65

def install_instance_methods(target)
  target.class_eval &instance_methods
end

#install_template_arg_methods(target, *args) ⇒ Object



54
55
56
57
58
59
# File 'lib/kindah/compiler.rb', line 54

def install_template_arg_methods(target, *args)
  each_parameter do |name, idx|
    target.define_singleton_method(name) { args[idx] }
    target.send(:define_method, name) { self.class.send(name) }
  end
end

#instance_methodsObject



13
14
15
# File 'lib/kindah/compiler.rb', line 13

def instance_methods
  safe_fetch InstanceMethods
end

#superklassObject



17
18
19
# File 'lib/kindah/compiler.rb', line 17

def superklass
  safe_fetch(Superklass, proc { Object }).call
end