Class: DbWords

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(argv = nil) ⇒ DbWords

Returns a new instance of DbWords.



7
8
9
10
11
12
# File 'lib/jwords/db_words.rb', line 7

def initialize(argv=nil)
  @argv = argv
  @words = Array.new
  @file = File.join(Dir.home, DATABASE_DIR, "#{DATABASE}.csv")
  create_db unless File.exist?(@file)
end

Instance Attribute Details

#wordsObject (readonly)

Returns the value of attribute words.



5
6
7
# File 'lib/jwords/db_words.rb', line 5

def words
  @words
end

Instance Method Details

#addObject

adding word in db



21
22
23
24
25
26
27
28
29
30
31
32
# File 'lib/jwords/db_words.rb', line 21

def add
  split
  if double?
    puts "You have '#{@words[0]}' in database"
    exit
  end

  CSV.open(@file, "a") do |csv|
    csv << [@words[0], @words[1]]
  end
  puts "Word is added"
end

#collectionObject

collecion of words



15
16
17
18
# File 'lib/jwords/db_words.rb', line 15

def collection
  col = CSV.read(@file)
  col
end

#destroyObject

Destroy a word from db file



35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/jwords/db_words.rb', line 35

def destroy
  list_w = collection
  @argv.map(&:to_i).each do |i|
    list_w.delete_at(i-1)
  end

  CSV.open(@file, "w") do |csv|
    list_w.each do |row|
      csv << row
    end
  end

  puts @argv.join(" ") + " deleted"
  list
end

#listObject

Print the list of words



66
67
68
69
70
# File 'lib/jwords/db_words.rb', line 66

def list
  list_of_words do |word, idx|
    puts "#{idx + 1} #{word[0]}: #{word[1]} | #{word[2]}"
  end
end

#update(index, updated_row) ⇒ Object



51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/jwords/db_words.rb', line 51

def update(index, updated_row)
  list_w = collection

  CSV.open(@file, "w") do |csv|
    list_w.each_with_index do |row, idx|
      if index == idx
        csv << updated_row
      else
        csv << row
      end
    end
  end
end