Class: CSVFile

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

Overview

That class helps to work with csv in pry or irb with some useful methods already defined. (Gem created just as a part of practice) PS: Stupid idea? if you think about it seriously more than 10 seconds? because almost everything work via CSV gem as you can see in require section

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(file_name: nil, file_extension: DefaultConstants::EXTENSION, convert: false, output: DefaultConstants::FILE_PATTERN) ⇒ CSVFile

initializer method for CSVFile



13
14
15
16
17
18
19
20
21
# File 'lib/csvn.rb', line 13

def initialize(file_name: nil, file_extension: DefaultConstants::EXTENSION, convert: false, output: DefaultConstants::FILE_PATTERN)
  @file_name = file_name                ### source file name (full path should be provided)
  @file_extension = file_extension      ### file extension
  @data = []                            ### file rows data
  @smart_convert = convert              ### convert readed data in array of hashes with file headers keys - false by default
  @file_headers = nil                   ### file headers array
  @read_flag = false                    ### service flag
  @output = output            ### write file name with extension
end

Instance Attribute Details

#dataObject

Returns the value of attribute data.



9
10
11
# File 'lib/csvn.rb', line 9

def data
  @data
end

#file_col_sepObject (readonly)

Returns the value of attribute file_col_sep.



10
11
12
# File 'lib/csvn.rb', line 10

def file_col_sep
  @file_col_sep
end

#file_extensionObject (readonly)

Returns the value of attribute file_extension.



10
11
12
# File 'lib/csvn.rb', line 10

def file_extension
  @file_extension
end

#file_headersObject

Returns the value of attribute file_headers.



9
10
11
# File 'lib/csvn.rb', line 9

def file_headers
  @file_headers
end

#file_nameObject

Returns the value of attribute file_name.



9
10
11
# File 'lib/csvn.rb', line 9

def file_name
  @file_name
end

#outputObject

Returns the value of attribute output.



9
10
11
# File 'lib/csvn.rb', line 9

def output
  @output
end

Instance Method Details

#delete(opts = {}) ⇒ Object



135
136
137
# File 'lib/csvn.rb', line 135

def delete(opts={})
  # opts - condition hash where :key is column value and :value - row value to chech for eql? with what you needed
end

#infoObject

Show some useful info about working file



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/csvn.rb', line 24

def info
  @encoding = find_enoding
  puts "INFO:"
  print 'File name         '; print "#{@file_name}\n".colorize(:green)
  print 'File headers      '; print "#{@file_headers}\n".colorize(:green)
  print 'File rows number  '; print "#{@data.size}\n".colorize(:green)
  print 'File encoding     '; print "#{@encoding}\n".colorize(:green)

  ## temp decision
  if @output_file_name
    print 'Output File   '; print "#{@output_file_name || 'nil'}\n".colorize(:green)
  end
end

#max(opts = {}) ⇒ Object



96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
# File 'lib/csvn.rb', line 96

def max(opts={})
  return ":by key must be provided for that method." unless opts[:by]

  raise_exceptions(__method__)

  value_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
  @data.max_by do |data_h|
    begin
      eval(value_statement)
    rescue NoMethodError => err
      puts err.message
      break
    end
  end
end

#mean(opts = {}) ⇒ Object



127
128
129
130
131
132
133
# File 'lib/csvn.rb', line 127

def mean(opts={})
  return ":by key must be provided for that method." unless opts[:by]
  raise_exceptions(__method__)

  mean_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
  @data.map { |data_h| eval(mean_statement) }.sum.to_f / @data.size
end

#min(opts = {}) ⇒ Object



112
113
114
115
116
117
118
119
120
121
122
123
124
125
# File 'lib/csvn.rb', line 112

def min(opts={})
  return ":by key must be provided for that method." unless opts[:by]
  raise_exceptions(__method__)

  value_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
  @data.min_by do |data_h|
    begin
      eval(value_statement)
    rescue NoMethodError => err
      puts err.message
      break
    end
  end
end

#readObject

Read dta from file Param :only can define limit of readed lines from file - not implemented yet



40
41
42
43
44
# File 'lib/csvn.rb', line 40

def read
  return if @read_flag

  process_reading
end

#select(opts = {}) ⇒ Object

Only for string row values will be improved to be able to handle more complex selecting like SQL does —-> multiple select



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

def select(opts = {})
  return @data.select { |row| row[opts[:where]] =~ /#{opts[:like]}/ } if opts[:like]
  return @data.select { |row| row[opts[:where]] !~ /#{opts[:not_like]}/ } if opts[:not_like]

  @data.select { |row| row[opts[:where]] == opts[:equals] }
end

#smart_convert!Object

Convert readed data to hash with headers keys Need to prevent reading only in one format and to give opportunity to choose data presentation



70
71
72
73
74
75
# File 'lib/csvn.rb', line 70

def smart_convert!
  if @file_headers.any?
    @data = @data.map { |d_arr| @file_headers.each_with_object({}).with_index { |(h_name, h_hash), ind| h_hash[h_name] = d_arr[ind] } }
    @smart_convert = true
  end
end

#sort(opts = {}) ⇒ Object



77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'lib/csvn.rb', line 77

def sort(opts={})
  return nil unless @data

  raise_exceptions(__method__)
  compare_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"

  sort_statement = <<-SORT_STATEMENT
    @data.sort_by do |data_h|
      begin
        eval(compare_statement)
      rescue NoMethodError => err
        puts err.message
        break
      end
    end#{opts[:desc] ? ".reverse" : ""}
  SORT_STATEMENT
  eval(sort_statement)
end

#write(data_to_write:, headers: [], encoding: DefaultConstants::ENCODING) ⇒ Object

Write data in file (named by pattern - may be found in DefaultConstants::FILE_PATTERN) Will write data every time it calles to ensure that all current data writed in file - may occurs duplicate if used more than once If data_to_write - is array of hashes - will use first hash keys as headers, else - headers that provided by :header key in method call



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

def write(data_to_write:, headers: [], encoding: DefaultConstants::ENCODING)
  data_prepared, headers_prepared = prepare_data_for_writing(data_to_write, headers)
  begin
    process_writing(data_prepared, headers_prepared, encoding)
    puts "Writed in #{@output}".colorize(:cyan)
  rescue StandardError => e2
    e2.message
  end
end