csvn 0.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: ec4c33e5fb6aaf2264302506e18e224c0462071f59bbbf923b35fda3752390e4
4
+ data.tar.gz: cfc4da29814350457d5bdbb3188a0d6a916f586ebfc56d49ece6acfbe5ddcffc
5
+ SHA512:
6
+ metadata.gz: cfbd4d677e663d0dab2694eb84e055eb33be3af06a363e631e1e68387af02c77791238ce9e4359677522203e2420ec0f839140f712c34be1b10f456f53c8dab7
7
+ data.tar.gz: fff66941b4a2e37c74ab612a77772ccb847422a7df3dda86316222a60319eeffe93471f2525443cefbb73a9c8de0410d5a77b9f46ee533032cb940384ae0e85a
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.3
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at shamrytski.d@profitero.com. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,7 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in csvn.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
7
+ gem "rspec", "~> 3.0"
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2021 shamrytski.d
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,44 @@
1
+ # Csvn
2
+
3
+ Welcome to your new gem! In this directory, you'll find the files you need to be able to package up your Ruby library into a gem. Put your Ruby code in the file `lib/csvn`. To experiment with that code, run `bin/console` for an interactive prompt.
4
+
5
+ TODO: Delete this and the text above, and describe your gem
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'csvn'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle install
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install csvn
22
+
23
+ ## Usage
24
+
25
+ TODO: Write usage instructions here
26
+
27
+ ## Development
28
+
29
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
30
+
31
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
32
+
33
+ ## Contributing
34
+
35
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/csvn. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [code of conduct](https://github.com/[USERNAME]/csvn/blob/master/CODE_OF_CONDUCT.md).
36
+
37
+
38
+ ## License
39
+
40
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
41
+
42
+ ## Code of Conduct
43
+
44
+ Everyone interacting in the Csvn project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/csvn/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "csvn"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
data/csvn.gemspec ADDED
@@ -0,0 +1,26 @@
1
+ require_relative 'lib/csvn/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = "csvn"
5
+ spec.version = Csvn::VERSION
6
+ spec.authors = ["shamritskiy3468"]
7
+ spec.email = ["sshamritskiy3468@gmail.com"]
8
+
9
+ spec.summary = %q{Simple attemp to simplify routine work with CSV file.}
10
+ spec.description = %q{Too lazy to write something, so use summary please :) }
11
+ spec.homepage = "https://github.com/shamritskiy3468/csvn"
12
+ spec.license = "MIT"
13
+ spec.required_ruby_version = Gem::Requirement.new(">= 2.3.0")
14
+
15
+ spec.metadata["homepage_uri"] = spec.homepage
16
+ spec.metadata["source_code_uri"] = "https://github.com/shamritskiy3468/csvn"
17
+
18
+ # Specify which files should be added to the gem when it is released.
19
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
20
+ spec.files = Dir.chdir(File.expand_path('..', __FILE__)) do
21
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
22
+ end
23
+ spec.bindir = "exe"
24
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
25
+ spec.require_paths = ["lib"]
26
+ end
data/lib/constants.rb ADDED
@@ -0,0 +1,7 @@
1
+ module DefaultConstants
2
+ ENCODING = "utf-8".freeze
3
+ EXTENSION = "csv".freeze
4
+ COL_SEPS = ["\t", ",", ";", " ", "|", ":"]
5
+ FILE_PATTERN = "cutsom_csv_output_#{Time.now.to_i.to_s}.csv".freeze
6
+ COL_SEP = "\t".freeze
7
+ end
@@ -0,0 +1,3 @@
1
+ module Csvn
2
+ VERSION = "0.1.2"
3
+ end
data/lib/csvn.rb ADDED
@@ -0,0 +1,226 @@
1
+ require "csvn/version"
2
+ require 'colorize'
3
+ require 'constants'
4
+ require 'csv'
5
+
6
+ # 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)
7
+ # 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
8
+ class CSVFile
9
+ attr_accessor :data, :file_headers, :output, :file_name
10
+ attr_reader :file_col_sep, :file_extension
11
+
12
+ # initializer method for CSVFile
13
+ def initialize(file_name: nil, file_extension: DefaultConstants::EXTENSION, convert: false, output: DefaultConstants::FILE_PATTERN)
14
+ raise StandardError unless file_name
15
+
16
+ @file_name = file_name ### source file name (full path should be provided)
17
+ @file_extension = file_extension ### file extension
18
+ @data = [] ### file rows data
19
+ @smart_convert = convert ### convert readed data in array of hashes with file headers keys - false by default
20
+ @file_headers = nil ### file headers array
21
+ @read_flag = false ### service flag
22
+ @output = output ### write file name with extension
23
+ end
24
+
25
+ # Show some useful info about working file
26
+ def info
27
+ @encoding = find_enoding
28
+ puts "INFO:"
29
+ print 'File name '; print "#{@file_name}\n".colorize(:green)
30
+ print 'File headers '; print "#{@file_headers}\n".colorize(:green)
31
+ print 'File rows number '; print "#{@data.size}\n".colorize(:green)
32
+ print 'File encoding '; print "#{@encoding}\n".colorize(:green)
33
+
34
+ ## temp decision
35
+ if @output_file_name
36
+ print 'Output File '; print "#{@output_file_name || 'nil'}\n".colorize(:green)
37
+ end
38
+ end
39
+
40
+ # Read dta from file
41
+ # Param :only can define limit of readed lines from file - not implemented yet
42
+ def read
43
+ return if @read_flag
44
+
45
+ process_reading
46
+ info
47
+ end
48
+
49
+ # Write data in file (named by pattern - may be found in DefaultConstants::FILE_PATTERN)
50
+ # Will write data every time it calles to ensure that all current data writed in file - may occurs duplicate if used more than once
51
+ # 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
52
+ def write(data_to_write:, headers: [], encoding: DefaultConstants::ENCODING)
53
+ data_prepared, headers_prepared = prepare_data_for_writing(data_to_write, headers)
54
+ begin
55
+ process_writing(data_prepared, headers_prepared, encoding)
56
+ puts "Writed in #{@output}".colorize(:cyan)
57
+ rescue StandardError => e2
58
+ e2.message
59
+ end
60
+ end
61
+
62
+ # Only for string row values
63
+ # will be improved to be able to handle more complex selecting like SQL does
64
+ def select(opts = {})
65
+ return @data.select { |row| row[opts[:where]] =~ /#{opts[:like]}/ } if opts[:like]
66
+ return @data.select { |row| row[opts[:where]] !~ /#{opts[:not_like]}/ } if opts[:not_like]
67
+
68
+ @data.select { |row| row[opts[:where]] == opts[:equals] }
69
+ end
70
+
71
+ # Convert readed data to hash with headers keys
72
+ # Need to prevent reading only in one format and to give opportunity to choose data presentation
73
+ def smart_convert!
74
+ if @file_headers.any?
75
+ @data = @data.map { |d_arr| @file_headers.each_with_object({}).with_index { |(h_name, h_hash), ind| h_hash[h_name] = d_arr[ind] } }
76
+ @smart_convert = true
77
+ end
78
+ end
79
+
80
+ def sort(opts={})
81
+ return nil unless @data
82
+
83
+ raise_exceptions(__method__)
84
+ compare_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
85
+
86
+ sort_statement = <<-SORT_STATEMENT
87
+ @data.sort_by do |data_h|
88
+ begin
89
+ eval(compare_statement)
90
+ rescue NoMethodError => err
91
+ puts err.message
92
+ break
93
+ end
94
+ end#{opts[:desc] ? ".reverse" : ""}
95
+ SORT_STATEMENT
96
+ eval(sort_statement)
97
+ end
98
+
99
+ def max(opts={})
100
+ return ":by key must be provided for that method." unless opts[:by]
101
+
102
+ raise_exceptions(__method__)
103
+
104
+ value_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
105
+ @data.max_by do |data_h|
106
+ begin
107
+ eval(value_statement)
108
+ rescue NoMethodError => err
109
+ puts err.message
110
+ break
111
+ end
112
+ end
113
+ end
114
+
115
+ def min(opts={})
116
+ return ":by key must be provided for that method." unless opts[:by]
117
+ raise_exceptions(__method__)
118
+
119
+ value_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
120
+ @data.min_by do |data_h|
121
+ begin
122
+ eval(value_statement)
123
+ rescue NoMethodError => err
124
+ puts err.message
125
+ break
126
+ end
127
+ end
128
+ end
129
+
130
+ def mean(opts={})
131
+ return ":by key must be provided for that method." unless opts[:by]
132
+ raise_exceptions(__method__)
133
+
134
+ mean_statement = opts[:apply] ? "data_h[opts[:by]].#{opts[:apply]}" : "data_h[opts[:by]]"
135
+ @data.map { |data_h| eval(mean_statement) }.sum.to_f / @data.size
136
+ end
137
+
138
+ def delete(opts={})
139
+ # opts - condition hash where :key is column value and :value - row value to chech for eql? with what you needed
140
+ end
141
+
142
+ private
143
+
144
+ # service methods that not need to be opened for usage outside
145
+ # if need more - contact please me or contribute yourself by merge request
146
+
147
+ def prepare_data_for_writing(data_to_write, headers)
148
+ if data_to_write.first.class.to_s.downcase =~ /hash/
149
+ prepared_headers = data_to_write.first.keys.map(&:to_s)
150
+ prepared_data_to_write = data_to_write.map { |data_h| data_h.values }
151
+ return prepared_data_to_write, prepared_headers
152
+ elsif data_to_write.first.class.to_s.downcase =~ /array/
153
+ raise "No headers provided for writing" if !headers or headers.empty?
154
+
155
+ return data_to_write, headers
156
+ end
157
+ end
158
+
159
+ def raise_exceptions(called_method)
160
+ raise "Need to <CSVFile instance>.smart_convert! your file data first to proceed #{called_method}." unless @smart_convert
161
+ raise "No data readed. Check these please before calling #{called_method}" unless @data
162
+ end
163
+
164
+ # find out file encoding
165
+ def find_enoding
166
+ scmdlog = `file -I #{@file_name}`.strip
167
+ scmdlog[/charset=(.+?)$/, 1]
168
+ end
169
+
170
+ # read data from file
171
+ def process_reading
172
+ begin
173
+ open_and_read_file
174
+ @read_flag = true
175
+ puts 'Success. Check instance fields'.colorize(:green)
176
+ rescue StandardError => e
177
+ puts e.message
178
+ end
179
+ end
180
+
181
+ # write data into file (upstream in <class>#write method)
182
+ def process_writing(data_to_write, headers, encoding)
183
+ begin
184
+ open_and_write_data(data_to_write, headers, encoding)
185
+ @write_flag = true
186
+ puts 'Success. Check file with new data'
187
+ rescue StandardError => e
188
+ puts e.message
189
+ rescue CSV::MalformedCSVError => e2
190
+ puts e2.message
191
+ end
192
+ end
193
+
194
+ def open_and_read_file
195
+ raise "No file name specified for reading data. Set file name with #{self.class}.file_name = <value>"
196
+ DefaultConstants::COL_SEPS.each do |separator|
197
+ begin
198
+ @file_col_sep = separator
199
+ @file_headers = nil
200
+ CSV.foreach(@file_name, col_sep: separator).with_index do |row_csv, row_index|
201
+ if row_index.zero?
202
+ @file_headers = row_csv
203
+ next
204
+ end
205
+ @data << row_csv
206
+ end
207
+
208
+ break
209
+ rescue CSV::MalformedCSVError => e
210
+ @file_headers = nil
211
+ next
212
+ rescue StandardError => e2
213
+ @file_headers = nil
214
+ next
215
+ end
216
+ end
217
+ end
218
+
219
+ def open_and_write_data(data, headers, encoding)
220
+ CSV.open(@output, 'w+', col_sep: DefaultConstants::COL_SEP, write_headers: true, headers: headers, encoding: encoding) do |csv_element|
221
+ data.each do |data_sample|
222
+ csv_element << data_sample
223
+ end
224
+ end
225
+ end
226
+ end
metadata ADDED
@@ -0,0 +1,57 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: csvn
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.2
5
+ platform: ruby
6
+ authors:
7
+ - shamritskiy3468
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2021-08-29 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: 'Too lazy to write something, so use summary please :) '
14
+ email:
15
+ - sshamritskiy3468@gmail.com
16
+ executables: []
17
+ extensions: []
18
+ extra_rdoc_files: []
19
+ files:
20
+ - ".travis.yml"
21
+ - CODE_OF_CONDUCT.md
22
+ - Gemfile
23
+ - LICENSE.txt
24
+ - README.md
25
+ - Rakefile
26
+ - bin/console
27
+ - bin/setup
28
+ - csvn.gemspec
29
+ - lib/constants.rb
30
+ - lib/csvn.rb
31
+ - lib/csvn/version.rb
32
+ homepage: https://github.com/shamritskiy3468/csvn
33
+ licenses:
34
+ - MIT
35
+ metadata:
36
+ homepage_uri: https://github.com/shamritskiy3468/csvn
37
+ source_code_uri: https://github.com/shamritskiy3468/csvn
38
+ post_install_message:
39
+ rdoc_options: []
40
+ require_paths:
41
+ - lib
42
+ required_ruby_version: !ruby/object:Gem::Requirement
43
+ requirements:
44
+ - - ">="
45
+ - !ruby/object:Gem::Version
46
+ version: 2.3.0
47
+ required_rubygems_version: !ruby/object:Gem::Requirement
48
+ requirements:
49
+ - - ">="
50
+ - !ruby/object:Gem::Version
51
+ version: '0'
52
+ requirements: []
53
+ rubygems_version: 3.0.8
54
+ signing_key:
55
+ specification_version: 4
56
+ summary: Simple attemp to simplify routine work with CSV file.
57
+ test_files: []