Class: LineBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/core_ext/line_builder.rb

Overview

Copyright @ weizhao 2012 把线性数据转化成对象的线性构造器 给定@data,@index就可以从 #object #all_object 方法中得到构造到的对象 一般需要重写 #process_line 行处理函数 #out? 退出条件处理函数

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(data, index = 0) ⇒ LineBuilder

Returns a new instance of LineBuilder.



9
10
11
12
13
14
15
16
# File 'lib/core_ext/line_builder.rb', line 9

def initialize(data,index=0)
	@data = data 			# 要处理的array数据
	@index = index 			# 处理数据的位置,从0起
	@data_size = data.size  # 这个会经常调用 
	@object = nil   		# 保存要构造的对象,调用#parse后可以使用
	@all_objects = nil 		# 保存所有能构造的对象, 调用#find_all后使用
	@is_parse = false  # 是否解析过的标志
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



8
9
10
# File 'lib/core_ext/line_builder.rb', line 8

def data
  @data
end

#indexObject

Returns the value of attribute index.



8
9
10
# File 'lib/core_ext/line_builder.rb', line 8

def index
  @index
end

Instance Method Details

#all_objectsObject



41
42
43
# File 'lib/core_ext/line_builder.rb', line 41

def all_objects
	@all_objects ||= find_all.collect { |b| b.object } 
end

#find_allObject

为@data结构全部的数据



74
75
76
77
78
# File 'lib/core_ext/line_builder.rb', line 74

def find_all
	return [] if is_over? && @object == nil  # 给定的index已经超出data
	parse unless @is_parse
	@all_objects = [self] + rest
end

#get_nextObject

得到下一个数据 运行两次不会得到下一个的下一个数据



63
64
65
66
# File 'lib/core_ext/line_builder.rb', line 63

def get_next
	return nil if is_over?
	return self.class.new(@data,@index).parse
end

#in?Boolean

进入条件,默认直接进入

Returns:

  • (Boolean)


47
48
49
# File 'lib/core_ext/line_builder.rb', line 47

def in?
	true
end

#is_over?Boolean

是否数据已经遍历结束

Returns:

  • (Boolean)


58
59
60
# File 'lib/core_ext/line_builder.rb', line 58

def is_over?
	@index >= @data_size
end

#objectObject



38
39
40
# File 'lib/core_ext/line_builder.rb', line 38

def object
	@object ||= parse.object
end

#out?Boolean

退出条件,默认为读完本行直接退出,重写要设置@index的新值 即线性构造器每次只取一行

Returns:

  • (Boolean)


54
55
56
# File 'lib/core_ext/line_builder.rb', line 54

def out?
	@index += 1
end

#parseObject

parse 分析函数,最好不要重写,一般这可就可以了



21
22
23
24
25
26
27
28
29
# File 'lib/core_ext/line_builder.rb', line 21

def parse
	@is_parse = true
	return nil if is_over?
	begin
		next unless in?
		process_line 
	end until (  out? || is_over?)
	self
end

#process_lineObject

行处理函数,必须被重写 默认是读一行,把数据做为对象传给object



34
35
36
37
# File 'lib/core_ext/line_builder.rb', line 34

def process_line
	line = @data[@index]
	@object = line
end

#restObject

得到剩下的数据



68
69
70
71
72
# File 'lib/core_ext/line_builder.rb', line 68

def rest
	return [] if is_over?
	next_b = get_next
	return [next_b] + next_b.rest #( next_b.is_over? ? [] : next_b.rest)
end