Class: Storage

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

Instance Method Summary collapse

Constructor Details

#initializeStorage

Returns a new instance of Storage.



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

def initialize
  @root = TreeNode.new
end

Instance Method Details

#add(str) ⇒ Object

adds new string to storage



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/storage.rb', line 13

def add(str)

  words = (str.split ",").map! { |word| word.strip }

  words.each do |word|
    node = @root
    word.split(//).each do |ch|
      node.children[ch]=TreeNode.new if node.children[ch].nil?

      node = node.children[ch]

    end
    node.is_leaf=true
  end
  @root.children
end

#contains(str) ⇒ Object

checks if storage contains string



32
33
34
35
36
37
38
39
40
41
42
# File 'lib/storage.rb', line 32

def contains(str)
  node = @root
  str.each_char do |ch|

    return false if node.children[ch].nil?

    node = node.children[ch]
  end
  node.is_leaf?

end

#find(str) ⇒ Object

returns all strings that start with str



46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/storage.rb', line 46

def find(str)
  node = @root
  str.each_char do |ch|

    return [] if node.children[ch].nil?

    node = node.children[ch]
  end
  words = []
  get_all_words node, str, words

  words
end

#load_from_file(file_name) ⇒ Object



61
62
63
64
65
# File 'lib/storage.rb', line 61

def load_from_file(file_name)
  file_to_read = File.open(file_name, "r")
  read_from_file file_to_read
  file_to_read.close
end

#load_from_zip(zip_name) ⇒ Object



75
76
77
78
79
80
81
# File 'lib/storage.rb', line 75

def load_from_zip (zip_name)
  zip_name = zip_name+".zip" unless zip_name.end_with? ".zip"
  Zip::ZipFile.foreach(zip_name) do |file|
    read_from_file file.get_input_stream
  end

end

#save_to_file(file_name) ⇒ Object



67
68
69
70
71
72
# File 'lib/storage.rb', line 67

def save_to_file(file_name)
  file_to_write = File.new(file_name, "w+")
  write_to_file file_to_write
  file_to_write.close

end

#save_to_zip(zip_name, result_file_name) ⇒ Object



83
84
85
86
87
88
89
90
91
# File 'lib/storage.rb', line 83

def save_to_zip (zip_name, result_file_name)
  zip_name = zip_name+".zip" unless zip_name.end_with? ".zip"
  Zip::ZipFile.open(zip_name, Zip::ZipFile::CREATE) do |zipfile|
    zipfile.get_output_stream(result_file_name)do |f|
      write_to_file f
    end
  end

end