csv_step_importer 0.3.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: de633f74f0d982cd785f8872a3a141ae8aa7877b3fe3994ddc7d57cc61e30898
4
+ data.tar.gz: 80fb26d62fb8e44e3828c20d9174e6141cd8adc6af5c7c32a85612157382d4da
5
+ SHA512:
6
+ metadata.gz: 69b8c793ef935985296b8916e373019863f7117ea08b577ca1519c2ef4722c9828b75d8f27a343be7833706a5bd96175831cf159a3a6041ada62052ee4714f35
7
+ data.tar.gz: 1e14c5bf9b64f89d125b2cdc61d49fc2a2d3b6f9aff47963e5903a2cd1e0683712786cf5adcf1456d508737497fc4bea95371bbd0e8afe842ed581b04d486873
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,9 @@
1
+ require: rubocop-rspec
2
+
3
+ inherit_gem:
4
+ rubocop-rails:
5
+ - config/rails.yml
6
+
7
+ AllCops:
8
+ TargetRubyVersion: 2.4
9
+ DisplayCopNames: true
data/.travis.yml ADDED
@@ -0,0 +1,5 @@
1
+ sudo: false
2
+ language: ruby
3
+ rvm:
4
+ - 2.4.3
5
+ before_install: gem install bundler -v 1.16.1
@@ -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 chris@fruwe.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 [http://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: http://contributor-covenant.org
74
+ [version]: http://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ git_source(:github) { |repo_name| "https://github.com/#{repo_name}" }
6
+
7
+ # Specify your gem's dependencies in csv_step_importer.gemspec
8
+ gemspec
data/Gemfile.lock ADDED
@@ -0,0 +1,121 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ csv_step_importer (0.2.8)
5
+ activemodel
6
+ activerecord-import
7
+ activesupport
8
+ smarter_csv
9
+
10
+ GEM
11
+ remote: https://rubygems.org/
12
+ specs:
13
+ actionpack (5.1.5)
14
+ actionview (= 5.1.5)
15
+ activesupport (= 5.1.5)
16
+ rack (~> 2.0)
17
+ rack-test (>= 0.6.3)
18
+ rails-dom-testing (~> 2.0)
19
+ rails-html-sanitizer (~> 1.0, >= 1.0.2)
20
+ actionview (5.1.5)
21
+ activesupport (= 5.1.5)
22
+ builder (~> 3.1)
23
+ erubi (~> 1.4)
24
+ rails-dom-testing (~> 2.0)
25
+ rails-html-sanitizer (~> 1.0, >= 1.0.3)
26
+ activemodel (5.1.5)
27
+ activesupport (= 5.1.5)
28
+ activerecord (5.1.5)
29
+ activemodel (= 5.1.5)
30
+ activesupport (= 5.1.5)
31
+ arel (~> 8.0)
32
+ activerecord-import (0.22.0)
33
+ activerecord (>= 3.2)
34
+ activesupport (5.1.5)
35
+ concurrent-ruby (~> 1.0, >= 1.0.2)
36
+ i18n (~> 0.7)
37
+ minitest (~> 5.1)
38
+ tzinfo (~> 1.1)
39
+ arel (8.0.0)
40
+ ast (2.4.0)
41
+ builder (3.2.3)
42
+ concurrent-ruby (1.0.5)
43
+ crass (1.0.3)
44
+ diff-lcs (1.3)
45
+ erubi (1.7.1)
46
+ i18n (0.9.5)
47
+ concurrent-ruby (~> 1.0)
48
+ loofah (2.2.1)
49
+ crass (~> 1.0.2)
50
+ nokogiri (>= 1.5.9)
51
+ method_source (0.9.0)
52
+ mini_portile2 (2.3.0)
53
+ minitest (5.11.3)
54
+ nokogiri (1.8.2)
55
+ mini_portile2 (~> 2.3.0)
56
+ parallel (1.12.1)
57
+ parser (2.5.0.4)
58
+ ast (~> 2.4.0)
59
+ powerpack (0.1.1)
60
+ rack (2.0.4)
61
+ rack-test (0.8.3)
62
+ rack (>= 1.0, < 3)
63
+ rails-dom-testing (2.0.3)
64
+ activesupport (>= 4.2.0)
65
+ nokogiri (>= 1.6)
66
+ rails-html-sanitizer (1.0.3)
67
+ loofah (~> 2.0)
68
+ railties (5.1.5)
69
+ actionpack (= 5.1.5)
70
+ activesupport (= 5.1.5)
71
+ method_source
72
+ rake (>= 0.8.7)
73
+ thor (>= 0.18.1, < 2.0)
74
+ rainbow (3.0.0)
75
+ rake (10.5.0)
76
+ rspec (3.7.0)
77
+ rspec-core (~> 3.7.0)
78
+ rspec-expectations (~> 3.7.0)
79
+ rspec-mocks (~> 3.7.0)
80
+ rspec-core (3.7.1)
81
+ rspec-support (~> 3.7.0)
82
+ rspec-expectations (3.7.0)
83
+ diff-lcs (>= 1.2.0, < 2.0)
84
+ rspec-support (~> 3.7.0)
85
+ rspec-mocks (3.7.0)
86
+ diff-lcs (>= 1.2.0, < 2.0)
87
+ rspec-support (~> 3.7.0)
88
+ rspec-support (3.7.1)
89
+ rubocop (0.53.0)
90
+ parallel (~> 1.10)
91
+ parser (>= 2.5)
92
+ powerpack (~> 0.1)
93
+ rainbow (>= 2.2.2, < 4.0)
94
+ ruby-progressbar (~> 1.7)
95
+ unicode-display_width (~> 1.0, >= 1.0.1)
96
+ rubocop-rails (1.2.2)
97
+ railties (>= 3.0)
98
+ rubocop (~> 0.49)
99
+ rubocop-rspec (1.24.0)
100
+ rubocop (>= 0.53.0)
101
+ ruby-progressbar (1.9.0)
102
+ smarter_csv (1.2.3)
103
+ thor (0.20.0)
104
+ thread_safe (0.3.6)
105
+ tzinfo (1.2.5)
106
+ thread_safe (~> 0.1)
107
+ unicode-display_width (1.3.0)
108
+
109
+ PLATFORMS
110
+ ruby
111
+
112
+ DEPENDENCIES
113
+ csv_step_importer!
114
+ bundler (~> 1.16)
115
+ rake (~> 10.0)
116
+ rspec (~> 3.0)
117
+ rubocop-rails
118
+ rubocop-rspec
119
+
120
+ BUNDLED WITH
121
+ 1.16.1
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2018 Christian-Manuel Butzke
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,43 @@
1
+ # CSVStepImporter
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/csv_step_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
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'csv_step_importer'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install csv_step_importer
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]/csv_step_importer. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
36
+
37
+ ## License
38
+
39
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
40
+
41
+ ## Code of Conduct
42
+
43
+ Everyone interacting in the CSVStepImporter project’s codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/csv_step_importer/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
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
+ task default: :spec
data/bin/console ADDED
@@ -0,0 +1,15 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "bundler/setup"
5
+ require "csv_step_importer"
6
+
7
+ # You can add fixtures and/or initialization code here to make experimenting
8
+ # with your gem easier. You can also use a different console, if you like.
9
+
10
+ # (If you use this, don't forget to add pry to your Gemfile!)
11
+ # require "pry"
12
+ # Pry.start
13
+
14
+ require "irb"
15
+ 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
@@ -0,0 +1,45 @@
1
+
2
+ # frozen_string_literal: true
3
+
4
+ lib = File.expand_path("../lib", __FILE__)
5
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
6
+ require "csv_step_importer/version"
7
+
8
+ Gem::Specification.new do |spec|
9
+ spec.name = "csv_step_importer"
10
+ spec.version = CSVStepImporter::VERSION
11
+ spec.authors = ["Christian-Manuel Butzke"]
12
+ spec.email = ["chris@fruwe.com"]
13
+
14
+ spec.summary = "Import your CSV files in multiple steps"
15
+ # spec.description = %q{TODO: Write a longer description or delete this line.}
16
+ spec.homepage = "https://github.com/fruwe/csv_step_importer"
17
+ spec.license = "MIT"
18
+
19
+ # Prevent pushing this gem to RubyGems.org. To allow pushes either set the 'allowed_push_host'
20
+ # to allow pushing to a single host or delete this section to allow pushing to any host.
21
+ # if spec.respond_to?(:metadata)
22
+ # spec.metadata["allowed_push_host"] = "TODO: Set to 'http://mygemserver.com'"
23
+ # else
24
+ # raise "RubyGems 2.0 or newer is required to protect against " \
25
+ # "public gem pushes."
26
+ # end
27
+
28
+ spec.files = `git ls-files -z`.split("\x0").reject do |f|
29
+ f.match(%r{^(test|spec|features)/})
30
+ end
31
+ spec.bindir = "exe"
32
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
33
+ spec.require_paths = ["lib"]
34
+
35
+ spec.add_development_dependency "bundler", "~> 1.16"
36
+ spec.add_development_dependency "rake", "~> 10.0"
37
+ spec.add_development_dependency "rspec", "~> 3.0"
38
+ spec.add_development_dependency "rubocop-rails"
39
+ spec.add_development_dependency "rubocop-rspec"
40
+
41
+ spec.add_dependency "activerecord-import"
42
+ spec.add_dependency "activesupport"
43
+ spec.add_dependency "activemodel"
44
+ spec.add_dependency "smarter_csv"
45
+ end
@@ -0,0 +1,67 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ class Base
5
+ include ::ActiveModel::Validations
6
+ include ::ActiveModel::Validations::Callbacks
7
+ include ::ActiveModel::Conversion
8
+ extend ::ActiveModel::Naming
9
+
10
+ define_callbacks :save
11
+
12
+ class CSVImportError < RuntimeError; end
13
+ class CSVFileImportError < CSVImportError; end
14
+
15
+ def assign_attributes(attributes)
16
+ attributes.each do |key, value|
17
+ send("#{key}=", value)
18
+ end
19
+ end
20
+
21
+ def persisted?
22
+ false
23
+ end
24
+
25
+ def create_or_update
26
+ raise "please extend and implement"
27
+ end
28
+
29
+ def save
30
+ run_callbacks :save do
31
+ return false unless valid?
32
+
33
+ status = !!::ActiveRecord::Base.transaction do
34
+ raise ::ActiveRecord::Rollback unless create_or_update
35
+ true
36
+ end
37
+
38
+ status
39
+ end
40
+ end
41
+
42
+ def save!
43
+ save || raise(CSVFileImportError.new(errors&.messages))
44
+ end
45
+
46
+ def update(attributes)
47
+ assign_attributes(attributes)
48
+ save
49
+ end
50
+
51
+ def inspect
52
+ to_s
53
+ end
54
+
55
+ def to_s
56
+ vars = self.instance_variables.map do |key|
57
+ next if key == :@children
58
+ next if key == :@parent
59
+ next if key == :@env
60
+ next if key == :@errors
61
+ next if key == :@cache
62
+ "#{key}=#{instance_variable_get(key).inspect}"
63
+ end.compact.join(", ")
64
+ "<#{self.class}: #{vars}>"
65
+ end
66
+ end
67
+ end
@@ -0,0 +1,31 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ class Chunk < CSVStepImporter::Node
5
+ attr_accessor :cache, :rows
6
+
7
+ def initialize(rows: [], row_class: CSVStepImporter::Row, processor_classes: nil, **attributes)
8
+ super **attributes
9
+
10
+ self.cache = {}
11
+ add_rows rows: rows, row_class: row_class
12
+ add_children processor_classes
13
+ end
14
+
15
+ def add_rows(rows:, row_class:)
16
+ row_parent_node = CSVStepImporter::Node.new parent: self
17
+
18
+ unless rows.empty? || rows.first.is_a?(row_class)
19
+ row_number = 0
20
+ rows = rows.collect do |row|
21
+ row_class.new(parent: row_parent_node, row_number: row_number += 1, **row)
22
+ end
23
+ end
24
+
25
+ @rows = rows
26
+
27
+ row_parent_node.add_children rows
28
+ add_children row_parent_node
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ class File < CSVStepImporter::Node
5
+ class CSVFileNotFoundError < CSVImportError; end
6
+
7
+ attr_accessor :chunk_class, :csv_options, :path, :row_class, :processor_classes, :csv_load_error
8
+
9
+ validates :chunk_class, presence: true
10
+ validates :csv_options, presence: true
11
+ validates :path, presence: true
12
+ validates :row_class, presence: true
13
+ validate :validate_csv_load_error
14
+
15
+ def initialize(path:, chunk_class: nil, row_class: nil, csv_options: {}, processor_classes: nil, **attributes)
16
+ super **attributes
17
+
18
+ self.chunk_class = chunk_class || CSVStepImporter::Chunk
19
+ self.path = path
20
+ self.row_class = row_class || CSVStepImporter::Row
21
+ self.processor_classes = processor_classes
22
+
23
+ self.csv_options = {
24
+ chunk_size: 1000,
25
+ file_encoding: "CP932:UTF-8",
26
+ }.merge(csv_options)
27
+
28
+ load_csv
29
+ end
30
+
31
+ def load_csv
32
+ raise CSVFileNotFoundError.new unless ::File.exists? path
33
+
34
+ ::SmarterCSV.process(path, **csv_options.deep_dup) do |rows|
35
+ add_children chunk_class.new parent: self, rows: rows, row_class: row_class, processor_classes: processor_classes
36
+ end
37
+ rescue EOFError
38
+ rescue CSVFileNotFoundError => exception
39
+ self.csv_load_error = exception
40
+ rescue ::CSV::MalformedCSVError => exception
41
+ self.csv_load_error = exception
42
+ end
43
+
44
+ def validate_csv_load_error
45
+ return unless csv_load_error
46
+ errors[:csv_file] << csv_load_error.message
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,46 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ module Model
5
+ class DAO < CSVStepImporter::Node
6
+ attr_accessor :id, :row
7
+
8
+ delegate :columns, to: :model
9
+
10
+ validates :row, presence: true
11
+
12
+ def initialize(row:, **attributes)
13
+ super **attributes
14
+
15
+ self.row = row
16
+ end
17
+
18
+ def model
19
+ parent.parent
20
+ end
21
+
22
+ def value
23
+ @value ||= columns.each_with_object({}) do |key, values|
24
+ values[key] = send key
25
+ end
26
+ end
27
+
28
+ def create_or_update
29
+ # Daoの保存処理は基本的にstepsで行います
30
+ true
31
+ end
32
+
33
+ def current_timestamp
34
+ model.cache[:updated_at] ||= ::Time.current.to_s(:db)
35
+ end
36
+
37
+ def created_at
38
+ current_timestamp
39
+ end
40
+
41
+ def updated_at
42
+ current_timestamp
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,47 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ module Model
5
+ class ImportableModel < CSVStepImporter::Model::Model
6
+ #########################################################
7
+ # Configuration
8
+ #########################################################
9
+
10
+ # example: User
11
+ def model_class
12
+ raise "please extend and implement"
13
+ end
14
+
15
+ def importer_class
16
+ CSVStepImporter::Model::Importer
17
+ end
18
+
19
+ def reflector_class
20
+ CSVStepImporter::Model::Reflector
21
+ end
22
+
23
+ # example: env[:company].company_users
24
+ def finder_scope
25
+ model_class.all
26
+ end
27
+
28
+ # example: [:email]
29
+ def finder_keys
30
+ raise "please extend and implement"
31
+ end
32
+
33
+ # example [:email, :updated_at]
34
+ def updatable_columns
35
+ raise "please extend and implement"
36
+ end
37
+
38
+ #########################################################
39
+ # Logic
40
+ #########################################################
41
+
42
+ def add_model_children
43
+ add_children [dao_node, importer_class, reflector_class], prepend: true
44
+ end
45
+ end
46
+ end
47
+ end
@@ -0,0 +1,41 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ module Model
5
+ class Importer < CSVStepImporter::Node
6
+ attr_accessor :dao_values
7
+
8
+ validate :validate_updatable_columns
9
+
10
+ delegate :model_class, to: :parent
11
+ delegate :columns, to: :parent
12
+ delegate :updatable_columns, to: :parent
13
+ delegate :dao_values, to: :parent
14
+
15
+ def create_or_update
16
+ model_class.import(
17
+ columns,
18
+ dao_values,
19
+ on_duplicate_key_update: updatable_columns,
20
+ validate: false,
21
+ timestamps: false,
22
+ )
23
+
24
+ true
25
+ end
26
+
27
+ def import(values)
28
+ self.values = values
29
+ save!
30
+ end
31
+
32
+ def validate_updatable_columns
33
+ return unless errors.empty?
34
+
35
+ if (updatable_columns - columns).present?
36
+ errors[:updatable_columns] << "updatedable_columns must be subset of columns"
37
+ end
38
+ end
39
+ end
40
+ end
41
+ end
@@ -0,0 +1,81 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "active_support/inflector"
4
+
5
+ module CSVStepImporter
6
+ module Model
7
+ class Model < CSVStepImporter::Node
8
+ attr_accessor :dao_values
9
+ delegate :rows, :cache, to: :parent
10
+
11
+ def initialize(**attributes)
12
+ super **attributes
13
+
14
+ add_daos
15
+ add_model_children
16
+ end
17
+
18
+ #########################################################
19
+ # Configuration
20
+ #########################################################
21
+
22
+ def self.cache_key
23
+ name.underscore.split("/").last.to_sym
24
+ end
25
+
26
+ # example: [:email, :updated_at, :created_at]
27
+ def columns
28
+ raise "please extend and implement"
29
+ end
30
+
31
+ def dao_class
32
+ CSVStepImporter::Model::DAO
33
+ end
34
+
35
+ #########################################################
36
+ # Logic
37
+ #########################################################
38
+
39
+ def add_model_children
40
+ add_children dao_node, prepend: true
41
+ end
42
+
43
+ def daos
44
+ dao_node.children
45
+ end
46
+
47
+ def dao_values
48
+ @dao_values ||= daos.collect(&:value)
49
+ end
50
+
51
+ def dao_node
52
+ @dao_node ||= CSVStepImporter::Node.new parent: self
53
+ end
54
+
55
+ def add_daos
56
+ dao_node_children = rows.collect do |row|
57
+ build_daos_for_row row
58
+ end.flatten.compact
59
+
60
+ link_rows_to_daos daos: dao_node_children
61
+
62
+ dao_node.add_children dao_node_children
63
+ end
64
+
65
+ # can return nil, a single object or an array of objects
66
+ def build_daos_for_row(row)
67
+ dao_class.new parent: dao_node, row: row
68
+ end
69
+
70
+ def link_rows_to_daos(daos:)
71
+ daos.each do |dao|
72
+ # add to cache with pluralized key
73
+ (dao.row.cache[self.class.cache_key.to_s.pluralize.to_sym] ||= []) << dao
74
+
75
+ # add dao to cache
76
+ dao.row.cache[self.class.cache_key] = dao
77
+ end
78
+ end
79
+ end
80
+ end
81
+ end
@@ -0,0 +1,50 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ module Model
5
+ class Reflector < CSVStepImporter::Node
6
+ delegate :model_class, to: :parent
7
+ delegate :finder_keys, to: :parent
8
+ delegate :finder_scope, to: :parent
9
+ delegate :finder_values, to: :parent
10
+ delegate :daos, to: :parent
11
+ delegate :name, to: :parent
12
+
13
+ def create_or_update
14
+ self.dao_ids = ids
15
+ true
16
+ end
17
+
18
+ def finder_key
19
+ raise "not yet supported" unless finder_keys.size == 1
20
+ finder_keys.first
21
+ end
22
+
23
+ def find_ids_scope
24
+ finder_scope
25
+ .where(finder_key => finder_values)
26
+ .order(["field(#{finder_key}, ?)", finder_values])
27
+ .pluck(:id)
28
+ end
29
+
30
+ def finder_values
31
+ @finder_values ||= daos.collect do |dao|
32
+ dao.value[finder_key]
33
+ end
34
+ end
35
+
36
+ def ids
37
+ @ids ||= find_ids_scope.to_a
38
+ end
39
+
40
+ # set ids
41
+ def dao_ids=(ids)
42
+ raise "Unable to find saved data. Please check your scope." unless ids.size == daos.size
43
+
44
+ daos.each_with_index do |dao, index|
45
+ dao.id = dao.value[:id] = ids[index]
46
+ end
47
+ end
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,59 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ class Node < CSVStepImporter::Base
5
+ attr_accessor :children
6
+ attr_accessor :parent
7
+
8
+ attr_accessor :env
9
+
10
+ delegate :cache, to: :root
11
+ delegate :root, to: :parent
12
+
13
+ validate :validate_children
14
+
15
+ def initialize(parent: nil, children: [], env: nil)
16
+ super()
17
+
18
+ self.env = env
19
+ self.parent = parent
20
+ self.children = children
21
+ end
22
+
23
+ def env
24
+ @env || parent&.env || {}.freeze
25
+ end
26
+
27
+ # childrenはHash型またはArray型です
28
+ def children=(children)
29
+ @children = []
30
+ add_children children
31
+ end
32
+
33
+ def add_children(children, prepend: false)
34
+ children = Array(children) unless children.is_a?(Enumerable)
35
+
36
+ children = children.collect do |child, sub_children|
37
+ next child unless child.is_a?(Class)
38
+ child.new parent: self, children: sub_children
39
+ end.compact
40
+
41
+ @children = prepend ? children + @children : @children + children
42
+ end
43
+
44
+ def create_or_update
45
+ children.empty? || children.all?(&:save)
46
+ end
47
+
48
+ def validate_children
49
+ return unless errors.empty?
50
+
51
+ children.each do |child|
52
+ next if child.valid?
53
+ child.errors.each do |key, message|
54
+ errors[key] << message
55
+ end
56
+ end
57
+ end
58
+ end
59
+ end
@@ -0,0 +1,19 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ class Row < CSVStepImporter::Node
5
+ attr_accessor :attributes, :cache, :row_number
6
+
7
+ def initialize(parent:, row_number:, **attributes)
8
+ super parent: parent
9
+
10
+ self.cache = {}
11
+ self.attributes = attributes
12
+ end
13
+
14
+ def create_or_update
15
+ # Rowの保存処理は基本的にstepsで行います
16
+ true
17
+ end
18
+ end
19
+ end
@@ -0,0 +1,5 @@
1
+ # frozen_string_literal: true
2
+
3
+ module CSVStepImporter
4
+ VERSION = "0.3.0"
5
+ end
@@ -0,0 +1,18 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "csv_step_importer/version"
4
+
5
+ require "csv_step_importer/base"
6
+ require "csv_step_importer/node"
7
+ require "csv_step_importer/row"
8
+ require "csv_step_importer/file"
9
+ require "csv_step_importer/chunk"
10
+ require "csv_step_importer/model/dao"
11
+ require "csv_step_importer/model/model"
12
+ require "csv_step_importer/model/reflector"
13
+ require "csv_step_importer/model/importer"
14
+ require "csv_step_importer/model/importable_model"
15
+
16
+ module CSVStepImporter
17
+ # Your code goes here...
18
+ end
metadata ADDED
@@ -0,0 +1,195 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: csv_step_importer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.3.0
5
+ platform: ruby
6
+ authors:
7
+ - Christian-Manuel Butzke
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2018-03-23 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.16'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.16'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: rspec
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '3.0'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '3.0'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rubocop-rails
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ">="
60
+ - !ruby/object:Gem::Version
61
+ version: '0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ">="
67
+ - !ruby/object:Gem::Version
68
+ version: '0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: rubocop-rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: activerecord-import
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :runtime
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ">="
95
+ - !ruby/object:Gem::Version
96
+ version: '0'
97
+ - !ruby/object:Gem::Dependency
98
+ name: activesupport
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :runtime
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ">="
109
+ - !ruby/object:Gem::Version
110
+ version: '0'
111
+ - !ruby/object:Gem::Dependency
112
+ name: activemodel
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :runtime
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: smarter_csv
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ type: :runtime
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ description:
140
+ email:
141
+ - chris@fruwe.com
142
+ executables: []
143
+ extensions: []
144
+ extra_rdoc_files: []
145
+ files:
146
+ - ".gitignore"
147
+ - ".rspec"
148
+ - ".rubocop.yml"
149
+ - ".travis.yml"
150
+ - CODE_OF_CONDUCT.md
151
+ - Gemfile
152
+ - Gemfile.lock
153
+ - LICENSE.txt
154
+ - README.md
155
+ - Rakefile
156
+ - bin/console
157
+ - bin/setup
158
+ - csv_step_importer.gemspec
159
+ - lib/csv_step_importer.rb
160
+ - lib/csv_step_importer/base.rb
161
+ - lib/csv_step_importer/chunk.rb
162
+ - lib/csv_step_importer/file.rb
163
+ - lib/csv_step_importer/model/dao.rb
164
+ - lib/csv_step_importer/model/importable_model.rb
165
+ - lib/csv_step_importer/model/importer.rb
166
+ - lib/csv_step_importer/model/model.rb
167
+ - lib/csv_step_importer/model/reflector.rb
168
+ - lib/csv_step_importer/node.rb
169
+ - lib/csv_step_importer/row.rb
170
+ - lib/csv_step_importer/version.rb
171
+ homepage: https://github.com/fruwe/csv_step_importer
172
+ licenses:
173
+ - MIT
174
+ metadata: {}
175
+ post_install_message:
176
+ rdoc_options: []
177
+ require_paths:
178
+ - lib
179
+ required_ruby_version: !ruby/object:Gem::Requirement
180
+ requirements:
181
+ - - ">="
182
+ - !ruby/object:Gem::Version
183
+ version: '0'
184
+ required_rubygems_version: !ruby/object:Gem::Requirement
185
+ requirements:
186
+ - - ">="
187
+ - !ruby/object:Gem::Version
188
+ version: '0'
189
+ requirements: []
190
+ rubyforge_project:
191
+ rubygems_version: 2.7.3
192
+ signing_key:
193
+ specification_version: 4
194
+ summary: Import your CSV files in multiple steps
195
+ test_files: []