Class: Utopia::TimeStore

Inherits:
Object
  • Object
show all
Defined in:
lib/utopia/time_store.rb

Overview

TimeStore is a very simple time oriented database. New entries are added in chronological order and it is not possible to change this behaviour, or remove old entries. It stores data in a CSV format into a directory where each file represents a week in the year.

The design of this class is to enable efficient logging of data in a backup friendly file format (i.e. files older than one week are not touched).

Due to the nature of CSV data, a header must be specified. This header can have columns added, but not removed. Columns not specified in the header will not be recorded.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(path, header) ⇒ TimeStore

Returns a new instance of TimeStore.



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
50
# File 'lib/utopia/time_store.rb', line 25

def initialize(path, header)
	@path = path

	header = header.collect{|name| name.to_s}

	@header_path = File.join(@path, "header.csv")

	if File.exist? @header_path
		@header = File.read(@header_path).split(",")
	else
		@header = []
	end

	diff = (Set.new(header) + "time") - @header

	if diff.size
		@header += diff.to_a.sort

		File.open(@header_path, "w") do |file|
			file.write(@header.join(","))
		end
	end
	
	@last_path = nil
	@last_file = nil
end

Instance Attribute Details

#headerObject (readonly)

Returns the value of attribute header.



52
53
54
# File 'lib/utopia/time_store.rb', line 52

def header
  @header
end

Instance Method Details

#<<(values) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/utopia/time_store.rb', line 82

def <<(values)
	time = values[:time] = Time.now

	open(time) do |file|
		file.puts(dump(values))
	end
end

#dump(values) ⇒ Object



77
78
79
80
# File 'lib/utopia/time_store.rb', line 77

def dump(values)
	row = @header.collect{|key| values[key.to_sym]}
	return CSV.generate_line(row)
end

#open(time) {|@last_file| ... } ⇒ Object

Yields:

  • (@last_file)


58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/utopia/time_store.rb', line 58

def open(time, &block)
	path = path_for_time(time)

	if @last_path != path
		if @last_file
			@last_file.close
			@last_file = nil
		end

		@last_file = File.open(path, "a")
		@last_file.sync = true
		@last_path = path
	end

	yield @last_file

	#File.open(path_for_time(time), "a", &block)
end

#path_for_time(time) ⇒ Object



54
55
56
# File 'lib/utopia/time_store.rb', line 54

def path_for_time(time)
	return File.join(@path, time.strftime("%Y-%W") + ".csv")
end