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



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

def class_name
  @ast.name
end

#compile!(location = Object) ⇒ Object



28
29
30
31
32
33
34
35
36
# File 'lib/kindah/compiler.rb', line 28

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

  location.send(:define_method, 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



38
39
40
41
42
43
44
45
46
# File 'lib/kindah/compiler.rb', line 38

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

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

#each_parameterObject



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

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



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

def install_class_methods(target)
  target.instance_eval &class_methods
end

#install_instance_methods(target) ⇒ Object



59
60
61
# File 'lib/kindah/compiler.rb', line 59

def install_instance_methods(target)
  target.class_eval &instance_methods
end

#install_template_arg_methods(target, *args) ⇒ Object



48
49
50
51
52
53
# File 'lib/kindah/compiler.rb', line 48

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