csvbuilder-importer 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 39d99815d9abc078be2c260b184249698061567e187610a592dff015fd0b8689
4
+ data.tar.gz: 9986a911e0afcfd82910e69c275b3f9082d10c2cf59d0597335310e491d2004a
5
+ SHA512:
6
+ metadata.gz: 1b6f735481aa24e1f06e2fb34dd6f9c7be5f09b31f9571d5542a2ac7eb1040d22144969fd2ac4fae5b3e3b0033546d49efac75fc0e514a056303653aa20c76bc
7
+ data.tar.gz: e43129b44151125b09f64d7aa6f14ae67c430e456a88a8858874f058a4f0b93af134c2bc05ded31d000e134caa4bbc23b9655ab718d4e4046c8880043d61d2f9
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,21 @@
1
+ inherit_from: .rubocop_todo.yml
2
+
3
+ require:
4
+ - rubocop-performance
5
+ - rubocop-rake
6
+ - rubocop-rspec
7
+
8
+ AllCops:
9
+ NewCops: enable
10
+ TargetRubyVersion: 2.6
11
+
12
+ Style/StringLiterals:
13
+ Enabled: true
14
+ EnforcedStyle: double_quotes
15
+
16
+ Style/StringLiteralsInInterpolation:
17
+ Enabled: true
18
+ EnforcedStyle: double_quotes
19
+
20
+ Layout/LineLength:
21
+ Max: 120
data/.rubocop_todo.yml ADDED
@@ -0,0 +1,92 @@
1
+ # This configuration was generated by
2
+ # `rubocop --auto-gen-config`
3
+ # on 2022-12-16 12:50:16 UTC using RuboCop version 1.39.0.
4
+ # The point is for the user to remove these configuration records
5
+ # one by one as the offenses are removed from the code base.
6
+ # Note that changes in the inspected code, or installation of new
7
+ # versions of RuboCop, may require this file to be generated again.
8
+
9
+ # Offense count: 5
10
+ # This cop supports safe autocorrection (--autocorrect).
11
+ # Configuration parameters: AllowHeredoc, AllowURI, URISchemes, IgnoreCopDirectives, AllowedPatterns, IgnoredPatterns.
12
+ # URISchemes: http, https
13
+ Layout/LineLength:
14
+ Max: 189
15
+ Exclude:
16
+ - 'lib/csvbuilder/importer/internal/import/csv.rb'
17
+ - 'lib/csvbuilder/importer/public/import/file.rb'
18
+ - 'spec/csvbuilder/importer/public/import/file_spec.rb'
19
+
20
+ # Offense count: 1
21
+ Lint/RescueException:
22
+ Exclude:
23
+ - 'lib/csvbuilder/importer/internal/import/csv.rb'
24
+
25
+ # Offense count: 2
26
+ # Configuration parameters: AllowedMethods, AllowedPatterns, IgnoredMethods, CountRepeatedAttributes.
27
+ Metrics/AbcSize:
28
+ Max: 22
29
+
30
+ # Offense count: 1
31
+ # Configuration parameters: CountComments, CountAsOne, ExcludedMethods, AllowedMethods, AllowedPatterns, IgnoredMethods, inherit_mode.
32
+ # AllowedMethods: refine
33
+ Metrics/BlockLength:
34
+ Max: 29
35
+
36
+ # Offense count: 1
37
+ # Configuration parameters: AllowedMethods, AllowedPatterns, IgnoredMethods.
38
+ Metrics/CyclomaticComplexity:
39
+ Max: 8
40
+
41
+ # Offense count: 2
42
+ # Configuration parameters: CountComments, CountAsOne, ExcludedMethods, AllowedMethods, AllowedPatterns, IgnoredMethods.
43
+ Metrics/MethodLength:
44
+ Max: 15
45
+
46
+ # Offense count: 2
47
+ # Configuration parameters: CountComments, CountAsOne.
48
+ Metrics/ModuleLength:
49
+ Max: 242
50
+
51
+ # Offense count: 7
52
+ # Configuration parameters: CountAsOne.
53
+ RSpec/ExampleLength:
54
+ Max: 15
55
+
56
+ # Offense count: 24
57
+ RSpec/MultipleExpectations:
58
+ Max: 13
59
+
60
+ # Offense count: 4
61
+ # Configuration parameters: AllowSubject.
62
+ RSpec/MultipleMemoizedHelpers:
63
+ Max: 7
64
+
65
+ # Offense count: 4
66
+ # Configuration parameters: AllowedGroups.
67
+ RSpec/NestedGroups:
68
+ Max: 5
69
+
70
+ # Offense count: 1
71
+ # Configuration parameters: AllowedPatterns.
72
+ # AllowedPatterns: ^expect_, ^assert_
73
+ RSpec/NoExpectationExample:
74
+ Exclude:
75
+ - 'spec/support/shared_examples/methods/define_attribute_method.rb'
76
+
77
+ # Offense count: 5
78
+ # Configuration parameters: AllowedConstants.
79
+ Style/Documentation:
80
+ Exclude:
81
+ - 'spec/**/*'
82
+ - 'test/**/*'
83
+ - 'lib/csvbuilder/importer/concerns/import/attributes.rb'
84
+ - 'lib/csvbuilder/importer/concerns/import/base.rb'
85
+ - 'lib/csvbuilder/importer/internal/import/attribute.rb'
86
+ - 'lib/csvbuilder/importer/public/import/file_model.rb'
87
+
88
+ # Offense count: 3
89
+ Style/OpenStructUse:
90
+ Exclude:
91
+ - 'spec/csvbuilder/importer/public/import/file_spec.rb'
92
+ - 'spec/support/fixtures/concerns/basic_attributes.rb'
data/CHANGELOG.md ADDED
@@ -0,0 +1,5 @@
1
+ ## [Unreleased]
2
+
3
+ ## [0.1.0] - 2022-12-16
4
+
5
+ - Initial release
@@ -0,0 +1,84 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
6
+
7
+ We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
8
+
9
+ ## Our Standards
10
+
11
+ Examples of behavior that contributes to a positive environment for our community include:
12
+
13
+ * Demonstrating empathy and kindness toward other people
14
+ * Being respectful of differing opinions, viewpoints, and experiences
15
+ * Giving and gracefully accepting constructive feedback
16
+ * Accepting responsibility and apologizing to those affected by our mistakes, and learning from the experience
17
+ * Focusing on what is best not just for us as individuals, but for the overall community
18
+
19
+ Examples of unacceptable behavior include:
20
+
21
+ * The use of sexualized language or imagery, and sexual attention or
22
+ advances of any kind
23
+ * Trolling, insulting or derogatory comments, and personal or political attacks
24
+ * Public or private harassment
25
+ * Publishing others' private information, such as a physical or email
26
+ address, without their explicit permission
27
+ * Other conduct which could reasonably be considered inappropriate in a
28
+ professional setting
29
+
30
+ ## Enforcement Responsibilities
31
+
32
+ Community leaders are responsible for clarifying and enforcing our standards of acceptable behavior and will take appropriate and fair corrective action in response to any behavior that they deem inappropriate, threatening, offensive, or harmful.
33
+
34
+ Community leaders have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, and will communicate reasons for moderation decisions when appropriate.
35
+
36
+ ## Scope
37
+
38
+ This Code of Conduct applies within all community spaces, and also applies when an individual is officially representing the community in public spaces. Examples of representing our community include using an official e-mail address, posting via an official social media account, or acting as an appointed representative at an online or offline event.
39
+
40
+ ## Enforcement
41
+
42
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported to the community leaders responsible for enforcement at joel.azemar@gmail.com. All complaints will be reviewed and investigated promptly and fairly.
43
+
44
+ All community leaders are obligated to respect the privacy and security of the reporter of any incident.
45
+
46
+ ## Enforcement Guidelines
47
+
48
+ Community leaders will follow these Community Impact Guidelines in determining the consequences for any action they deem in violation of this Code of Conduct:
49
+
50
+ ### 1. Correction
51
+
52
+ **Community Impact**: Use of inappropriate language or other behavior deemed unprofessional or unwelcome in the community.
53
+
54
+ **Consequence**: A private, written warning from community leaders, providing clarity around the nature of the violation and an explanation of why the behavior was inappropriate. A public apology may be requested.
55
+
56
+ ### 2. Warning
57
+
58
+ **Community Impact**: A violation through a single incident or series of actions.
59
+
60
+ **Consequence**: A warning with consequences for continued behavior. No interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, for a specified period of time. This includes avoiding interactions in community spaces as well as external channels like social media. Violating these terms may lead to a temporary or permanent ban.
61
+
62
+ ### 3. Temporary Ban
63
+
64
+ **Community Impact**: A serious violation of community standards, including sustained inappropriate behavior.
65
+
66
+ **Consequence**: A temporary ban from any sort of interaction or public communication with the community for a specified period of time. No public or private interaction with the people involved, including unsolicited interaction with those enforcing the Code of Conduct, is allowed during this period. Violating these terms may lead to a permanent ban.
67
+
68
+ ### 4. Permanent Ban
69
+
70
+ **Community Impact**: Demonstrating a pattern of violation of community standards, including sustained inappropriate behavior, harassment of an individual, or aggression toward or disparagement of classes of individuals.
71
+
72
+ **Consequence**: A permanent ban from any sort of public interaction within the community.
73
+
74
+ ## Attribution
75
+
76
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 2.0,
77
+ available at https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
78
+
79
+ Community Impact Guidelines were inspired by [Mozilla's code of conduct enforcement ladder](https://github.com/mozilla/diversity).
80
+
81
+ [homepage]: https://www.contributor-covenant.org
82
+
83
+ For answers to common questions about this code of conduct, see the FAQ at
84
+ https://www.contributor-covenant.org/faq. Translations are available at https://www.contributor-covenant.org/translations.
data/Gemfile ADDED
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in csvbuilder-importer.gemspec
6
+ gemspec
7
+
8
+ gem "rake"
9
+
10
+ gem "rspec"
11
+
12
+ gem "rubocop"
13
+
14
+ gem "rubocop-performance"
15
+ gem "rubocop-rake"
16
+ gem "rubocop-rspec"
17
+
18
+ gem "csvbuilder-core", path: "../csvbuilder-core"
data/Gemfile.lock ADDED
@@ -0,0 +1,92 @@
1
+ PATH
2
+ remote: ../csvbuilder-core
3
+ specs:
4
+ csvbuilder-core (0.1.1)
5
+ activesupport (~> 6.1)
6
+
7
+ PATH
8
+ remote: .
9
+ specs:
10
+ csvbuilder-importer (0.1.0)
11
+ activemodel (~> 6.1)
12
+ activesupport (~> 6.1)
13
+ csvbuilder-core (= 0.1.1)
14
+
15
+ GEM
16
+ remote: https://rubygems.org/
17
+ specs:
18
+ activemodel (6.1.7)
19
+ activesupport (= 6.1.7)
20
+ activesupport (6.1.7)
21
+ concurrent-ruby (~> 1.0, >= 1.0.2)
22
+ i18n (>= 1.6, < 2)
23
+ minitest (>= 5.1)
24
+ tzinfo (~> 2.0)
25
+ zeitwerk (~> 2.3)
26
+ ast (2.4.2)
27
+ concurrent-ruby (1.1.10)
28
+ diff-lcs (1.5.0)
29
+ i18n (1.12.0)
30
+ concurrent-ruby (~> 1.0)
31
+ json (2.6.3)
32
+ minitest (5.16.3)
33
+ parallel (1.22.1)
34
+ parser (3.1.3.0)
35
+ ast (~> 2.4.1)
36
+ rainbow (3.1.1)
37
+ rake (13.0.6)
38
+ regexp_parser (2.6.1)
39
+ rexml (3.2.5)
40
+ rspec (3.12.0)
41
+ rspec-core (~> 3.12.0)
42
+ rspec-expectations (~> 3.12.0)
43
+ rspec-mocks (~> 3.12.0)
44
+ rspec-core (3.12.0)
45
+ rspec-support (~> 3.12.0)
46
+ rspec-expectations (3.12.0)
47
+ diff-lcs (>= 1.2.0, < 2.0)
48
+ rspec-support (~> 3.12.0)
49
+ rspec-mocks (3.12.0)
50
+ diff-lcs (>= 1.2.0, < 2.0)
51
+ rspec-support (~> 3.12.0)
52
+ rspec-support (3.12.0)
53
+ rubocop (1.40.0)
54
+ json (~> 2.3)
55
+ parallel (~> 1.10)
56
+ parser (>= 3.1.2.1)
57
+ rainbow (>= 2.2.2, < 4.0)
58
+ regexp_parser (>= 1.8, < 3.0)
59
+ rexml (>= 3.2.5, < 4.0)
60
+ rubocop-ast (>= 1.23.0, < 2.0)
61
+ ruby-progressbar (~> 1.7)
62
+ unicode-display_width (>= 1.4.0, < 3.0)
63
+ rubocop-ast (1.24.0)
64
+ parser (>= 3.1.1.0)
65
+ rubocop-performance (1.15.1)
66
+ rubocop (>= 1.7.0, < 2.0)
67
+ rubocop-ast (>= 0.4.0)
68
+ rubocop-rake (0.6.0)
69
+ rubocop (~> 1.0)
70
+ rubocop-rspec (2.15.0)
71
+ rubocop (~> 1.33)
72
+ ruby-progressbar (1.11.0)
73
+ tzinfo (2.0.5)
74
+ concurrent-ruby (~> 1.0)
75
+ unicode-display_width (2.3.0)
76
+ zeitwerk (2.6.6)
77
+
78
+ PLATFORMS
79
+ x86_64-darwin-21
80
+
81
+ DEPENDENCIES
82
+ csvbuilder-core!
83
+ csvbuilder-importer!
84
+ rake
85
+ rspec
86
+ rubocop
87
+ rubocop-performance
88
+ rubocop-rake
89
+ rubocop-rspec
90
+
91
+ BUNDLED WITH
92
+ 2.3.22
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Joel Azemar
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,37 @@
1
+ # Csvbuilder::Importer
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/csvbuilder/importer`. 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
+ Install the gem and add to the application's Gemfile by executing:
10
+
11
+ $ bundle add csvbuilder-importer
12
+
13
+ If bundler is not being used to manage dependencies, install the gem by executing:
14
+
15
+ $ gem install csvbuilder-importer
16
+
17
+ ## Usage
18
+
19
+ TODO: Write usage instructions here
20
+
21
+ ## Development
22
+
23
+ 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.
24
+
25
+ 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 the created tag, and push the `.gem` file to [rubygems.org](https://rubygems.org).
26
+
27
+ ## Contributing
28
+
29
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/csvbuilder-importer. 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]/csvbuilder-importer/blob/main/CODE_OF_CONDUCT.md).
30
+
31
+ ## License
32
+
33
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
34
+
35
+ ## Code of Conduct
36
+
37
+ Everyone interacting in the Csvbuilder::Importer project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/csvbuilder-importer/blob/main/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,14 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "bundler/gem_tasks"
4
+ require "rspec/core/rake_task"
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ require "rubocop/rake_task"
9
+
10
+ RuboCop::RakeTask.new(:rubocop) do |task|
11
+ task.options = ["-A"]
12
+ end
13
+
14
+ task default: %i[spec rubocop]
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Runtime dependencies
6
+ gem "activesupport", "~> 5.2"
7
+ gem "activemodel", "~> 5.2"
8
+ gem "csvbuilder-core", "0.1.1"
9
+
10
+ # Development dependencies
11
+ gem "rake"
12
+ gem "rspec"
13
+ gem "rubocop"
14
+ gem "rubocop-performance"
15
+ gem "rubocop-rake"
16
+ gem "rubocop-rspec"
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Runtime dependencies
6
+ gem "activesupport", "~> 6.1"
7
+ gem "activemodel", "~> 6.1"
8
+ gem "csvbuilder-core", "0.1.1"
9
+
10
+ # Development dependencies
11
+ gem "rake"
12
+ gem "rspec"
13
+ gem "rubocop"
14
+ gem "rubocop-performance"
15
+ gem "rubocop-rake"
16
+ gem "rubocop-rspec"
@@ -0,0 +1,16 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Runtime dependencies
6
+ gem "activesupport", "~> 7.0"
7
+ gem "activemodel", "~> 7.0"
8
+ gem "csvbuilder-core", "0.1.1"
9
+
10
+ # Development dependencies
11
+ gem "rake"
12
+ gem "rspec"
13
+ gem "rubocop"
14
+ gem "rubocop-performance"
15
+ gem "rubocop-rake"
16
+ gem "rubocop-rspec"
@@ -0,0 +1,54 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csvbuilder/core/concerns/attributes_base"
4
+
5
+ require "csvbuilder/importer/internal/import/attribute"
6
+
7
+ module Csvbuilder
8
+ module Import
9
+ module Attributes
10
+ extend ActiveSupport::Concern
11
+ include AttributesBase
12
+
13
+ included do
14
+ ensure_attribute_method
15
+ end
16
+
17
+ def valid?(*args)
18
+ is_valid = super
19
+
20
+ # The method attribute_objects was called by the valid? method through
21
+ # the attribute getters. The memoization must be cleared now to propagate
22
+ # the errors into the Attribute(s).
23
+ instance_variable_set(:@attribute_objects, nil) unless is_valid
24
+
25
+ is_valid
26
+ end
27
+
28
+ def attribute_objects
29
+ @attribute_objects ||= _attribute_objects(errors)
30
+ end
31
+
32
+ protected
33
+
34
+ def _attribute_objects(attributes_errors = {})
35
+ index = -1
36
+
37
+ array_to_block_hash(self.class.column_names) do |column_name|
38
+ Attribute.new(column_name, source_row[index += 1], attributes_errors[column_name], self)
39
+ end
40
+ end
41
+
42
+ class_methods do
43
+ def define_attribute_method(column_name)
44
+ # return if super { original_attribute(column_name) }.nil?
45
+ super do
46
+ return unless @attribute_objects
47
+
48
+ @attribute_objects[column_name].try(:value)
49
+ end
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Csvbuilder
4
+ module Import
5
+ module Base
6
+ extend ActiveSupport::Concern
7
+
8
+ included do
9
+ attr_reader :source_headers, :source_row, :line_number, :index, :previous
10
+
11
+ validate { errors.add(:csv, "has #{@csv_exception.message}") if @csv_exception }
12
+ end
13
+
14
+ # @param [Array] source_row_or_exception the csv row
15
+ # @param options [Hash]
16
+ # @option options [Integer] :index 1st row_model is 0, 2nd is 1, 3rd is 2, etc.
17
+ # @option options [Integer] :line_number line_number in the CSV file
18
+ # @option options [Array] :source_headers the csv header row
19
+ # @option options [Csvbuilder::Import] :previous the previous row model
20
+ # @option options [Csvbuilder::Import] :parent if the instance is a child, pass the parent
21
+ def initialize(source_row_or_exception = [], options = {})
22
+ @source_row = source_row_or_exception
23
+ @csv_exception = source_row if source_row.is_a? Exception
24
+ @source_row = [] if source_row_or_exception.class != Array
25
+
26
+ @line_number = options[:line_number]
27
+ @index = options[:index]
28
+ @source_headers = options[:source_headers]
29
+
30
+ @previous = options[:previous].try(:dup)
31
+
32
+ previous.try(:free_previous)
33
+
34
+ super(options)
35
+ end
36
+
37
+ # Free `previous` from memory to avoid making a linked list
38
+ def free_previous
39
+ attributes
40
+ @previous = nil
41
+ end
42
+
43
+ # Safe to override.
44
+ #
45
+ # @return [Boolean] returns true, if this instance should be skipped
46
+ def skip?
47
+ !valid?
48
+ end
49
+
50
+ # Safe to override.
51
+ #
52
+ # @return [Boolean] returns true, if the entire csv file should stop reading
53
+ def abort?
54
+ false
55
+ end
56
+
57
+ class_methods do
58
+ #
59
+ # Move to Import::File once FileModel is removed.
60
+ #
61
+ # @param [Import::File] file to read from
62
+ # @param [Hash] context extra data you want to work with the model
63
+ # @param [Import] prevuous the previous row model
64
+ # @return [Import] the next model instance from the csv
65
+ def next(file, context = {})
66
+ csv = file.csv
67
+
68
+ csv.skip_headers
69
+ csv.read_row
70
+
71
+ new(csv.current_row,
72
+ line_number: csv.line_number,
73
+ index: file.index,
74
+ source_headers: csv.headers,
75
+ context: context,
76
+ previous: file.previous_row_model)
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csvbuilder/core/internal/attribute_base"
4
+
5
+ module Csvbuilder
6
+ module Import
7
+ class Attribute < Csvbuilder::AttributeBase
8
+ attr_reader :source_value, :attribute_errors
9
+
10
+ def initialize(column_name, source_value, attribute_errors, row_model)
11
+ @source_value = source_value
12
+ @attribute_errors = attribute_errors
13
+
14
+ super(column_name, row_model)
15
+ end
16
+
17
+ def value
18
+ @value ||= if attribute_errors.present?
19
+ nil
20
+ else
21
+ formatted_value
22
+ end
23
+ end
24
+
25
+ def parsed_value
26
+ @parsed_value ||= formatted_value
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,99 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Csvbuilder
4
+ module Import
5
+ # Abstraction of Ruby's CSV library. Keeps current row and line_number, skips empty rows, handles errors.
6
+ class Csv
7
+ # @return [String] the file path of the CSV
8
+ attr_reader :file_path
9
+ # @return [Integer, nil] return `0` at start of file, `1 to infinity` is line_number of row_model, `nil` is end of file (row is also `nil`)
10
+ attr_reader :line_number
11
+ # @return [Array, nil] the current row, or nil at the beginning or end of file
12
+ attr_reader :current_row
13
+
14
+ include ActiveModel::Validations
15
+
16
+ validate { begin; _ruby_csv; rescue StandardError => e; errors.add(:csv, e.message) end }
17
+
18
+ def initialize(file_path)
19
+ @file_path = file_path
20
+ reset
21
+ end
22
+
23
+ # http://stackoverflow.com/questions/2650517/count-the-number-of-lines-in-a-file-without-reading-entire-file-into-memory
24
+ # @return [Integer] the number of rows in the file, including empty new lines
25
+ def size
26
+ @size ||= `wc -l #{file_path}`.split[0].to_i + 1
27
+ end
28
+
29
+ # If the current position is at the headers, skip it and return it. Otherwise, only return false.
30
+ # @return [Boolean, Array] returns false, if header is already skipped, otherwise returns the header
31
+ def skip_headers
32
+ start_of_file? ? (@headers = read_row) : false
33
+ end
34
+
35
+ # Returns the header __without__ changing the position of the CSV
36
+ # @return [Array, nil] the header
37
+ def headers
38
+ @headers ||= next_row
39
+ end
40
+
41
+ # Resets the file to the start of file
42
+ def reset
43
+ return false unless valid?
44
+
45
+ @line_number = 0
46
+ @headers = @current_row = @next_row = @skipped_rows = @next_skipped_rows = nil
47
+
48
+ @ruby_csv.try(:close)
49
+ @ruby_csv = _ruby_csv
50
+
51
+ true
52
+ end
53
+
54
+ # @return [Boolean] true, if the current position is at the start of the file
55
+ def start_of_file?
56
+ line_number.zero?
57
+ end
58
+
59
+ # @return [Boolean] true, if the current position is at the end of the file
60
+ def end_of_file?
61
+ line_number.nil?
62
+ end
63
+
64
+ # Returns the next row __without__ changing the position of the CSV
65
+ # @return [Array, nil] the next row, or `nil` at the end of file
66
+ def next_row
67
+ @next_row ||= _read_row
68
+ end
69
+
70
+ # Returns the next row, while changing the position of the CSV
71
+ # @return [Array, nil] the changed current row, or `nil` at the end of file
72
+ def read_row
73
+ return if end_of_file?
74
+
75
+ @current_row = @next_row || _read_row
76
+ @line_number = current_row.nil? ? nil : @line_number + 1
77
+ @next_row = nil
78
+
79
+ current_row
80
+ end
81
+
82
+ protected
83
+
84
+ def _ruby_csv
85
+ CSV.open(file_path)
86
+ end
87
+
88
+ def _read_row
89
+ return unless valid?
90
+
91
+ @ruby_csv.readline.tap { |row| @headers ||= row }
92
+ rescue Exception => e
93
+ changed = e.exception(e.message.gsub(/line \d+\.?/, "line #{line_number + 1}.")) # line numbers are usually off
94
+ changed.set_backtrace(e.backtrace)
95
+ changed
96
+ end
97
+ end
98
+ end
99
+ end
@@ -0,0 +1,127 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csvbuilder/importer/internal/import/csv"
4
+
5
+ module Csvbuilder
6
+ module Import
7
+ # Represents a csv file and handles parsing to return `Import`
8
+ class File
9
+ extend ActiveModel::Callbacks
10
+ include ActiveModel::Validations
11
+
12
+ attr_reader :csv, :row_model_class, :index, :current_row_model, :previous_row_model, :context # -1 = start of file, 0 to infinity = index of row_model, nil = end of file, no row_model
13
+
14
+ delegate :size, :end_of_file?, :line_number, to: :csv
15
+
16
+ define_model_callbacks :each_iteration
17
+ define_model_callbacks :next
18
+ define_model_callbacks :abort, :skip, only: :before
19
+
20
+ validate { errors.merge!(csv.errors) unless csv.valid? }
21
+
22
+ # @param [String] file_path path of csv file
23
+ # @param [Import] row_model_class model class returned for importing
24
+ # @param context [Hash] context passed to the {Import}
25
+ def initialize(file_path, row_model_class, context = {})
26
+ @csv = ::Csvbuilder::Import::Csv.new(file_path) # Full namespace provided to avoid confusion with Ruby CSV class.
27
+ @row_model_class = row_model_class
28
+ @context = context.to_h.symbolize_keys
29
+ reset
30
+ end
31
+
32
+ def headers
33
+ h = csv.headers
34
+ h.instance_of?(Array) ? h : []
35
+ end
36
+
37
+ # Resets the file back to the top
38
+ def reset
39
+ csv.reset
40
+ @index = -1
41
+ @current_row_model = nil
42
+ end
43
+
44
+ # Gets the next row model based on the context
45
+ def next(context = {})
46
+ return if end_of_file?
47
+
48
+ run_callbacks :next do
49
+ context = context.to_h.reverse_merge(self.context)
50
+ @previous_row_model = current_row_model
51
+ @index += 1
52
+ @current_row_model = row_model_class.next(self, context)
53
+ @current_row_model = @index = nil if end_of_file?
54
+ end
55
+
56
+ current_row_model
57
+ end
58
+
59
+ # Iterates through the entire csv file and provides the `current_row_model` in a block, while handing aborts and skips
60
+ # via. calling {Model#abort?} and {Model#skip?}
61
+ def each(context = {})
62
+ return to_enum(__callee__, context) unless block_given?
63
+ return false if _abort?
64
+
65
+ while self.next(context)
66
+ run_callbacks :each_iteration do
67
+ return false if _abort?
68
+ next if _skip?
69
+
70
+ yield current_row_model
71
+ end
72
+ end
73
+ end
74
+
75
+ # @return [Boolean] returns true, if the file should abort reading
76
+ def abort?
77
+ !valid? || !!current_row_model.try(:abort?)
78
+ end
79
+
80
+ # @return [Boolean] returns true, if the file should skip `current_row_model`
81
+ def skip?
82
+ !!current_row_model.try(:skip?)
83
+ end
84
+
85
+ protected
86
+
87
+ def _abort?
88
+ abort = abort?
89
+ run_callbacks(:abort) if abort
90
+ abort
91
+ end
92
+
93
+ def _skip?
94
+ skip = skip?
95
+ run_callbacks(:skip) if skip
96
+ skip
97
+ end
98
+
99
+ #
100
+ # Validations
101
+ #
102
+ def headers_invalid_row
103
+ errors.add(:csv, "has header with #{csv.headers.message}") if csv.headers.class < Exception
104
+ end
105
+
106
+ def headers_count
107
+ return if headers_invalid_row || !csv.valid?
108
+ return if row_model_class.try(:row_names) # FileModel check
109
+
110
+ size_until_blank = ((headers || []).map { |h| h.try(:strip) }.rindex(&:present?) || -1) + 1
111
+ column_names = row_model_class.column_names
112
+
113
+ return if size_until_blank == column_names.size
114
+
115
+ expected_headers_size = column_names.size
116
+
117
+ message = [
118
+ "count does not match.",
119
+ " Given headers (#{size_until_blank}).",
120
+ " Expected headers (#{expected_headers_size}): #{column_names.join(", ")}"
121
+ ]
122
+
123
+ errors.add(:headers, message.join)
124
+ end
125
+ end
126
+ end
127
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csvbuilder/core/public/model"
4
+ require "csvbuilder/importer/concerns/import/base"
5
+ require "csvbuilder/importer/concerns/import/attributes"
6
+
7
+ module Csvbuilder
8
+ # Include this to with {Model} to have a RowModel for importing csvs.
9
+ module Import
10
+ extend ActiveSupport::Concern
11
+
12
+ include Csvbuilder::Model
13
+
14
+ include ActiveModel::Validations
15
+
16
+ include Base
17
+ include Attributes
18
+ end
19
+ end
@@ -0,0 +1,7 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Csvbuilder
4
+ module Importer
5
+ VERSION = "0.1.0"
6
+ end
7
+ end
@@ -0,0 +1,17 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csvbuilder/importer/version"
4
+
5
+ require "csv"
6
+ require "ostruct"
7
+ require "active_model"
8
+
9
+ require "active_support"
10
+ require "active_support/dependencies/autoload"
11
+ require "active_support/core_ext/object"
12
+ require "active_support/core_ext/string"
13
+
14
+ require "csvbuilder/core"
15
+
16
+ require "csvbuilder/importer/public/import"
17
+ require "csvbuilder/importer/public/import/file"
@@ -0,0 +1,6 @@
1
+ module Csvbuilder
2
+ module Importer
3
+ VERSION: String
4
+ # See the writing guide of rbs: https://github.com/ruby/rbs#guides
5
+ end
6
+ end
metadata ADDED
@@ -0,0 +1,111 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: csvbuilder-importer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Joel Azemar
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2022-12-19 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activemodel
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '6.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '6.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '6.1'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '6.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: csvbuilder-core
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - '='
46
+ - !ruby/object:Gem::Version
47
+ version: 0.1.1
48
+ type: :runtime
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - '='
53
+ - !ruby/object:Gem::Version
54
+ version: 0.1.1
55
+ description: Help handle CSVs in a more efficient way
56
+ email:
57
+ - joel.azemar@gmail.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".rspec"
63
+ - ".rubocop.yml"
64
+ - ".rubocop_todo.yml"
65
+ - CHANGELOG.md
66
+ - CODE_OF_CONDUCT.md
67
+ - Gemfile
68
+ - Gemfile.lock
69
+ - LICENSE.txt
70
+ - README.md
71
+ - Rakefile
72
+ - gemfiles/Gemfile.5.2._gemfile
73
+ - gemfiles/Gemfile.6.1._gemfile
74
+ - gemfiles/Gemfile.7.0._gemfile
75
+ - lib/csvbuilder/importer.rb
76
+ - lib/csvbuilder/importer/concerns/import/attributes.rb
77
+ - lib/csvbuilder/importer/concerns/import/base.rb
78
+ - lib/csvbuilder/importer/internal/import/attribute.rb
79
+ - lib/csvbuilder/importer/internal/import/csv.rb
80
+ - lib/csvbuilder/importer/public/import.rb
81
+ - lib/csvbuilder/importer/public/import/file.rb
82
+ - lib/csvbuilder/importer/version.rb
83
+ - sig/csvbuilder/importer.rbs
84
+ homepage: https://github.com/joel/csvbuilder-importer
85
+ licenses:
86
+ - MIT
87
+ metadata:
88
+ homepage_uri: https://github.com/joel/csvbuilder-importer
89
+ source_code_uri: https://github.com/joel/csvbuilder-importer
90
+ changelog_uri: https://github.com/joel/csvbuilder-importer/blob/main/CHANGELOG.md
91
+ rubygems_mfa_required: 'true'
92
+ post_install_message:
93
+ rdoc_options: []
94
+ require_paths:
95
+ - lib
96
+ required_ruby_version: !ruby/object:Gem::Requirement
97
+ requirements:
98
+ - - ">="
99
+ - !ruby/object:Gem::Version
100
+ version: 2.6.0
101
+ required_rubygems_version: !ruby/object:Gem::Requirement
102
+ requirements:
103
+ - - ">="
104
+ - !ruby/object:Gem::Version
105
+ version: '0'
106
+ requirements: []
107
+ rubygems_version: 3.3.12
108
+ signing_key:
109
+ specification_version: 4
110
+ summary: Csvbuilder Importer contain the components to handle CSV importing
111
+ test_files: []