active_admin_importer 0.1.0

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
+ SHA1:
3
+ metadata.gz: c4469bf0e26ddf3c84800aed672a1729c0893b06
4
+ data.tar.gz: b85ef234d5ed264bb327f2d4936a79e245032827
5
+ SHA512:
6
+ metadata.gz: 8f84bb74980ef292b9946ec7bf1105f81ff1ee574becf5389e41e317d38d2a6d9623d1de016a26f00233781e2f0daee81f51795336f6ebe8dd3e02c318322dfb
7
+ data.tar.gz: d6d117b5e3f695b6f56d17c30676961e661457b76aff559244fac8db8cdf72fd31a202fb226d8aab401901b2f49c42a021de5e665b74a8adaeeebbdc1eb41bfb
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.3.0
4
+ before_install: gem install bundler -v 1.11.2
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in active_admin_importer.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2017 Jason Ayre
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,68 @@
1
+ # ActiveAdminImporter
2
+
3
+ Simple CSV imports for active_admin, that (shouldn't) destroy your servers memory.
4
+
5
+ ### Features / differences from similar gems
6
+ 1. Parses the CSV file one row at a time
7
+ 2. Allows you to override the view to customize the form
8
+ 3. Access to the current controller from the import definition
9
+ 4. Can define any number of imports per resource
10
+
11
+ ### Examples
12
+
13
+ ``` ruby
14
+ ::ActiveAdmin.register Product do
15
+ define_import_for :products do |model, import_params, controller|
16
+ product_attributes = import_params.slice(*[:name, :price])
17
+ product_attributes[:user_id] = controller.current_user.id
18
+ model.create!(product_attributes)
19
+ end
20
+
21
+ #Example: require headers to be present
22
+ define_import_for :products_on_sale, :required_headers => ["sale_price"] do |model, import_params, controller|
23
+ product_attributes = import_params.slice(*[:name, :price, :sale_price])
24
+ product_attributes[:user_id] = controller.current_user.id
25
+ model.create!(product_attributes)
26
+ end
27
+
28
+ # Example: using a custom view
29
+ # assume the view has a dropdown which allows you to select a particular store during import
30
+ define_import_for :products_for_store, :view => "myactiveadmin/products/upload_products_for_store_csv"
31
+ do |model, import_params, controller|
32
+ product_attributes = import_params.slice(*[:name, :price, :sale_price])
33
+ product_attributes[:user_id] = controller.current_user.id
34
+ product_attributes[:store_id] = controller.params["store_id"]
35
+ model.create!(product_attributes)
36
+ end
37
+ end
38
+ ```
39
+
40
+ ## Installation
41
+
42
+ Add this line to your application's Gemfile:
43
+
44
+ ```ruby
45
+ gem 'active_admin_importer'
46
+ ```
47
+
48
+ And then execute:
49
+
50
+ $ bundle
51
+
52
+ Or install it yourself as:
53
+
54
+ $ gem install active_admin_importer
55
+
56
+ ## Development
57
+
58
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `bundle exec rspec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
59
+
60
+ 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).
61
+
62
+ ## Contributing
63
+
64
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/active_admin_importer.
65
+
66
+ ## License
67
+
68
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
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
@@ -0,0 +1,39 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'active_admin_importer/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "active_admin_importer"
8
+ spec.version = ActiveAdminImporter::VERSION
9
+ spec.authors = ["Jason Ayre"]
10
+ spec.email = ["jayre@peer60.com"]
11
+
12
+ spec.summary = %q{ActiveAdmin CSV Importer gem}
13
+ spec.description = %q{Import CSV's into activeadmin}
14
+ spec.homepage = "https://github.com/jasonayre/active_admin_importer"
15
+ spec.license = "MIT"
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ # end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = "exe"
27
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
28
+ spec.require_paths = ["lib"]
29
+
30
+ spec.add_development_dependency "bundler", "~> 1.11"
31
+ spec.add_development_dependency "rake", "~> 10.0"
32
+ spec.add_development_dependency "rails", "~> 4.2"
33
+ spec.add_development_dependency "activeadmin", "~> 1.0.0.pre5"
34
+ spec.add_development_dependency "rspec", "~> 3.0"
35
+ spec.add_development_dependency "rspec-pride"
36
+ spec.add_development_dependency "pry-nav"
37
+
38
+ spec.add_dependency "activesupport"
39
+ end
@@ -0,0 +1,17 @@
1
+ <%= form_for :dump, :url => {:action => target_action}, :html => {:multipart => true} do |f| %>
2
+ <table>
3
+ <tr>
4
+ <td>
5
+ <%= label_tag "dump_file", "Select a CSV File" %>
6
+ </td>
7
+ <td>
8
+ <%= f.file_field :file %>
9
+ </td>
10
+ </tr>
11
+ <tr>
12
+ <td>
13
+ <%= submit_tag 'Submit' %>
14
+ </td>
15
+ </tr>
16
+ </table>
17
+ <% end %>
@@ -0,0 +1,17 @@
1
+ <%= form_for :dump, :url => {:action => "import_csv"}, :html => {:multipart => true} do |f| %>
2
+ <table>
3
+ <tr>
4
+ <td>
5
+ <%= label_tag "dump_file", "Select a CSV File" %>
6
+ </td>
7
+ <td>
8
+ <%= f.file_field :file %>
9
+ </td>
10
+ </tr>
11
+ <tr>
12
+ <td>
13
+ <%= submit_tag 'Submit' %>
14
+ </td>
15
+ </tr>
16
+ </table>
17
+ <% end %>
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "active_admin_importer"
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
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,46 @@
1
+ require 'csv'
2
+ require 'digest'
3
+
4
+ module ActiveAdminImporter
5
+ class CsvFile < SimpleDelegator
6
+ CSV_READ_OPTIONS = { :headers => true, :header_converters => :symbol }.freeze
7
+
8
+ def self.read(path)
9
+ new(::File.new(path))
10
+ end
11
+
12
+ def initialize(descriptor)
13
+ @descriptor = descriptor
14
+ end
15
+
16
+ def __getobj__
17
+ @descriptor
18
+ end
19
+
20
+ def each_row(&block)
21
+ ::CSV.parse(self, CSV_READ_OPTIONS, &block)
22
+ end
23
+
24
+ def find_row_by_number(number)
25
+ result = ::CSV.foreach(self, CSV_READ_OPTIONS).with_index do |row, i|
26
+ return row if i == number - 1
27
+ end
28
+
29
+ result
30
+ end
31
+
32
+ def headers
33
+ @headers ||= ::CSV.open(@descriptor, 'r') { |csv| csv.first }
34
+ end
35
+
36
+ # read file in chunks for memory efficiency
37
+ def md5
38
+ @md5 ||= ::File.open(@descriptor, "rb") do |io|
39
+ _md5 = ::Digest::MD5.new
40
+ buffer = ""
41
+ _md5.update(buffer) while io.read(4096, buffer)
42
+ _md5
43
+ end
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,29 @@
1
+ module ActiveAdminImporter
2
+ module DSL
3
+ def define_import_for(name='records', **options, &block)
4
+ options[:action] ||= "import_#{name}"
5
+ options[:form_action] ||= "upload_#{name}"
6
+ options[:view] ||= "admin/csv/upload"
7
+ options[:required_headers] ||= []
8
+
9
+ action_item :edit, :only => :index do
10
+ link_to options[:action].titleize, :action => options[:form_action]
11
+ end
12
+
13
+ collection_action(options[:form_action]) do
14
+ render options[:view], :locals => { :target_action => options[:action] }
15
+ end
16
+
17
+ collection_action(options[:action], :method => :post) do
18
+ parent if parent?
19
+ import = ::ActiveAdminImporter.import(params[:dump][:file],
20
+ :model => active_admin_config.resource_class,
21
+ :controller => self,
22
+ :required_headers => options[:required_headers],
23
+ &block)
24
+
25
+ redirect_to collection_path(), alert: import.result
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,12 @@
1
+ require 'rails'
2
+
3
+ module ActiveAdminImporter
4
+ class Engine < ::Rails::Engine
5
+ config.mount_at = '/'
6
+
7
+ config.after_initialize do
8
+ require "active_admin"
9
+ ::ActiveAdmin::DSL.send(:include, ActiveAdminImporter::DSL)
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,82 @@
1
+ module ActiveAdminImporter
2
+ class Import
3
+ attr_reader :current_row, :csv_file
4
+
5
+ def initialize(csv_file, controller:, model:, required_headers:[], &block)
6
+ @csv_file = ::ActiveAdminImporter::CsvFile.new(csv_file)
7
+ @controller = controller
8
+ @model = model
9
+ @required_headers = required_headers
10
+ @current_row = 0
11
+ @block = block if block_given?
12
+ end
13
+
14
+ def failed_rows
15
+ @failed_rows ||= []
16
+ end
17
+
18
+ def headers
19
+ @headers ||= @csv_file.headers
20
+ end
21
+
22
+ def run
23
+ log_info("STARTING IMPORT")
24
+
25
+ ::CSV.parse(@csv_file, :headers => true, :header_converters => :symbol) do |row|
26
+ begin
27
+ process_row(row)
28
+ rescue => e
29
+ record_failure(row, e)
30
+ end
31
+ end
32
+
33
+ log_error("FAILED TO PARSE ROWS #{failed_rows}") if failed_rows.any?
34
+ log_info("FINISHED IMPORT")
35
+ end
36
+
37
+ def result
38
+ @result ||= begin
39
+ _result = []
40
+ _result << "Bad column headers, expected #{@required_headers} got #{@csv_file.headers}" unless self.valid?
41
+ _result << "Failed to import rows: #{failed_rows.join(',')}" if failed_rows.any?
42
+ _result << "#{current_row - failed_rows.length} / #{current_row} imported successfully" if current_row > 0
43
+ _result.join("\n")
44
+ end
45
+ end
46
+
47
+ def valid?
48
+ @required_headers.all?{ |header| self.headers.include?(header) }
49
+ end
50
+
51
+ private
52
+
53
+ def process_row(row)
54
+ @current_row += 1
55
+ log_info("IMPORTING ROW - #{current_row}")
56
+ data = row.to_hash
57
+
58
+ if data.present?
59
+ if @block
60
+ @block.call(@model, data, @controller)
61
+ else
62
+ @model.create!(data)
63
+ end
64
+ end
65
+ end
66
+
67
+ def record_failure(row, e)
68
+ log_error("FAILED TO PARSE ROW #{current_row}")
69
+ failed_rows << current_row
70
+ log_error("ERROR_ON_ROW\##{current_row} - #{e.message}")
71
+ ::Rails.logger.error(e.message)
72
+ end
73
+
74
+ def log_error(message)
75
+ ::Rails.logger.error("[IMPORT: #{@csv_file.md5}]: #{message}")
76
+ end
77
+
78
+ def log_info(message)
79
+ ::Rails.logger.info("[IMPORT: #{@csv_file.md5}]: #{message}")
80
+ end
81
+ end
82
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveAdminImporter
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,25 @@
1
+ require "active_admin_importer/version"
2
+ require "active_support/all"
3
+ require "active_admin_importer/engine"
4
+
5
+ module ActiveAdminImporter
6
+ extend ::ActiveSupport::Autoload
7
+
8
+ autoload :DSL
9
+ autoload :Engine
10
+ autoload :CsvFile
11
+ autoload :Import
12
+
13
+ def self.import(csv_file, **options, &block)
14
+ io = csv_file.is_a?(::ActionDispatch::Http::UploadedFile) ? csv_file.tempfile : csv_file
15
+
16
+ _import = if block_given?
17
+ ::ActiveAdminImporter::Import.new(io, **options, &block)
18
+ else
19
+ ::ActiveAdminImporter::Import.new(io, **options)
20
+ end
21
+
22
+ _import.run if _import.valid?
23
+ _import
24
+ end
25
+ end
metadata ADDED
@@ -0,0 +1,174 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_admin_importer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jason Ayre
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2017-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.11'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.11'
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: rails
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '4.2'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '4.2'
55
+ - !ruby/object:Gem::Dependency
56
+ name: activeadmin
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: 1.0.0.pre5
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: 1.0.0.pre5
69
+ - !ruby/object:Gem::Dependency
70
+ name: rspec
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - "~>"
74
+ - !ruby/object:Gem::Version
75
+ version: '3.0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - "~>"
81
+ - !ruby/object:Gem::Version
82
+ version: '3.0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: rspec-pride
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ">="
88
+ - !ruby/object:Gem::Version
89
+ version: '0'
90
+ type: :development
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: pry-nav
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ">="
102
+ - !ruby/object:Gem::Version
103
+ version: '0'
104
+ type: :development
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: activesupport
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
+ description: Import CSV's into activeadmin
126
+ email:
127
+ - jayre@peer60.com
128
+ executables: []
129
+ extensions: []
130
+ extra_rdoc_files: []
131
+ files:
132
+ - ".gitignore"
133
+ - ".rspec"
134
+ - ".travis.yml"
135
+ - Gemfile
136
+ - LICENSE.txt
137
+ - README.md
138
+ - Rakefile
139
+ - active_admin_importer.gemspec
140
+ - app/views/admin/csv/upload.html.erb
141
+ - app/views/admin/csv/upload_csv.html.erb
142
+ - bin/console
143
+ - bin/setup
144
+ - lib/active_admin_importer.rb
145
+ - lib/active_admin_importer/csv_file.rb
146
+ - lib/active_admin_importer/dsl.rb
147
+ - lib/active_admin_importer/engine.rb
148
+ - lib/active_admin_importer/import.rb
149
+ - lib/active_admin_importer/version.rb
150
+ homepage: https://github.com/jasonayre/active_admin_importer
151
+ licenses:
152
+ - MIT
153
+ metadata: {}
154
+ post_install_message:
155
+ rdoc_options: []
156
+ require_paths:
157
+ - lib
158
+ required_ruby_version: !ruby/object:Gem::Requirement
159
+ requirements:
160
+ - - ">="
161
+ - !ruby/object:Gem::Version
162
+ version: '0'
163
+ required_rubygems_version: !ruby/object:Gem::Requirement
164
+ requirements:
165
+ - - ">="
166
+ - !ruby/object:Gem::Version
167
+ version: '0'
168
+ requirements: []
169
+ rubyforge_project:
170
+ rubygems_version: 2.5.1
171
+ signing_key:
172
+ specification_version: 4
173
+ summary: ActiveAdmin CSV Importer gem
174
+ test_files: []