Class: Cocoadex::Serializer

Inherits:
Object
  • Object
show all
Defined in:
lib/cocoadex/serializer.rb

Overview

Move data to and from disk

Constant Summary collapse

SEPARATOR =
"--__--"

Class Method Summary collapse

Class Method Details

.check_path(path) ⇒ Object

Ensure parent paths exist



19
20
21
22
23
# File 'lib/cocoadex/serializer.rb', line 19

def self.check_path path
  unless File.exists? File.dirname(path)
    FileUtils.mkdir_p File.dirname(path)
  end
end

.read(path) ⇒ Object

Read a serialized cache file into an Array



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

def self.read path
  $/=SEPARATOR
  array = []
  File.open(path, "r").each do |object|
    array << Marshal::load(object)
  end
  array
end

.style_to_mode(style) ⇒ Object



50
51
52
53
54
55
56
57
# File 'lib/cocoadex/serializer.rb', line 50

def self.style_to_mode style
  case style
    when :append then 'a'
    when :overwrite then 'w'
    else
      raise "Unknown file mode: #{style}"
  end
end

.write_array(path, array, style) ⇒ Object

Write a cache Array as a serialized file



37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/cocoadex/serializer.rb', line 37

def self.write_array path, array, style
  check_path path

  mode = style_to_mode(style)

  File.open(path, mode) do |file|
    array.each do |object|
      file.print(Marshal.dump(object))
      file.print SEPARATOR
    end
  end
end

.write_text(path, text, style = :overwrite) ⇒ Object

Write text to a file



26
27
28
29
30
31
32
33
34
# File 'lib/cocoadex/serializer.rb', line 26

def self.write_text path, text, style=:overwrite
  check_path path

  mode = style_to_mode(style)

  File.open(path, 'w') do |file|
    file.print text
  end
end