Class: Kaiseki::Node

Inherits:
Object show all
Defined in:
lib/node.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(args = [], global = nil) ⇒ Node

Returns a new instance of Node.



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/node.rb', line 3

def initialize args = [], global = nil
	args.must_be Array
	if global
		global.each_pair do |key, value|
			instance_variable_set key.to_instance_variable, value
		end
	end
	list = args.reverse
	self.class.arg_names.each do |name|
		value = []
		while 0 >= self.class.arity[name] or value.length < self.class.arity[name]
			if !list.empty?
				value << list.pop
			elsif value.empty? and self.class.defaults.key?(name)
				value << self.class.defaults[name]
				break
			else
				if self.class.arity[name] <= 0
					break
				else
					raise ArgumentError, "wrong number of arguments (#{value.length} for #{self.class.arity[name]})"
				end
			end
		end
		if self.class.arity[name] == 1
			value = value[0]
		elsif self.class.arity[name] == 0
			if value.length < 1
				value = nil
			elsif value.length == 1
				value = value[0]
			end
		end
		instance_variable_set name.to_instance_variable, value
	end
end

Class Method Details

.arg_namesObject



70
71
72
# File 'lib/node.rb', line 70

def arg_names
	[]
end

.arityObject



74
75
76
# File 'lib/node.rb', line 74

def arity
	{}
end

.bind(args, options = {}) ⇒ Object



61
62
63
64
65
66
67
68
# File 'lib/node.rb', line 61

def bind args, options = {}
	args.must_be Array
	raise "can't bind parent NodeClass" if self == Node
	define_singleton_method(:arg_names) { args }
	define_singleton_method(:arity) { Hash.new {|hash, key| 1 }.merge(options[:arity] || {}) }
	define_singleton_method(:defaults) { options[:defaults] || {} }
	self
end

.defaultObject



57
58
59
# File 'lib/node.rb', line 57

def default
	subclass [:result], :arity => {:result => 0}
end

.defaultsObject



78
79
80
# File 'lib/node.rb', line 78

def defaults
	{}
end

.subclass(args, options = {}) ⇒ Object



52
53
54
55
# File 'lib/node.rb', line 52

def subclass args, options = {}
	args.must_be Array
	Class.new(self).bind args, options
end

Instance Method Details

#eval(global = nil, &block) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/node.rb', line 40

def eval global = nil, &block
	value = instance_eval &block
	if global
		(instance_variables.collect {|n| n.from_instance_variable } - self.class.arg_names).each do |n|
			global[n] = instance_variable_get n.to_instance_variable
		end
	end
	value
end