Class: MyActiveRecord::CsvAdapter

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

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ CsvAdapter

Returns a new instance of CsvAdapter.



5
6
7
8
# File 'lib/my_active_record/csv_adapter.rb', line 5

def initialize(params)
  @db_path = params[:db_path]
  raise "DB path is not set" unless @db_path
end

Instance Method Details

#insert(table_name, row) ⇒ Object



28
29
30
31
32
# File 'lib/my_active_record/csv_adapter.rb', line 28

def insert(table_name, row)
  CSV.open(path_to_table(table_name), "ab") do |csv|
    csv << row
  end
end

#last(table_name) ⇒ Object



47
48
49
# File 'lib/my_active_record/csv_adapter.rb', line 47

def last(table_name)
  read_table(table_name).last
end

#load_table_schema(table_name) ⇒ Object



10
11
12
13
14
15
# File 'lib/my_active_record/csv_adapter.rb', line 10

def load_table_schema(table_name)
  raise("Csv file #{table_name}.csv should be created") unless File.exists?(path_to_table(table_name))
  schema = CSV.table(path_to_table(table_name)).headers
  raise("ID column should exist") unless schema.include?(:id)
  schema
end

#update(table_name, row) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/my_active_record/csv_adapter.rb', line 34

def update(table_name, row)
  old_csv = read_table(table_name)
  CSV.open(path_to_table(table_name), "wb") do |csv|
    old_csv.each do |old_row|
      if row[0] == old_row[0]
        csv << row
      else
        csv << old_row
      end
    end
  end
end

#where(table_name, params) ⇒ Object



17
18
19
20
21
22
23
24
25
26
# File 'lib/my_active_record/csv_adapter.rb', line 17

def where(table_name, params)
  results = []
  read_table(table_name).each do |row|
    all_terms_succeded = params.all? do |key,value|
      row[table_schema(table_name).find_index(key.to_sym)].to_s == value.to_s
    end
    results << row if all_terms_succeded
  end
  results
end