cure 0.1.1

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: 4991d1e0e8328be48a27ab4ed1dc099cc57f0b0ebd1ae1add6763fca4908d9c3
4
+ data.tar.gz: 477a17c2ba7052657d54facea23056f9ad07068b6e3596810da4ae7cfb79d51a
5
+ SHA512:
6
+ metadata.gz: ee5600adcd1052493ef5db828cc43830e5d758dfb153d849afddb1f3e7a209606036cc238d425081d3d9724ed4cb3d9ee7466dd49df6b80c37711ab25aa53172
7
+ data.tar.gz: d49ccb85c6bfc5414b666f49395683ef2a751ff7af19c2f380af94aebdda835de8c8cd8bc4dbca17c426d91cb64a2254b35456b204e7327352ba8de97a232747
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.rubocop.yml ADDED
@@ -0,0 +1,132 @@
1
+ AllCops:
2
+ TargetRubyVersion: 2.6
3
+
4
+ Style/StringLiterals:
5
+ Enabled: true
6
+ EnforcedStyle: double_quotes
7
+
8
+ Style/StringLiteralsInInterpolation:
9
+ Enabled: true
10
+ EnforcedStyle: double_quotes
11
+
12
+ Layout/LineLength:
13
+ Max: 120
14
+
15
+ # Too short methods lead to extraction of single-use methods, which can make
16
+ # the code easier to read (by naming things), but can also clutter the class
17
+ Metrics/MethodLength:
18
+ Max: 20
19
+
20
+ # The guiding principle of classes is SRP, SRP can't be accurately measured by LoC
21
+ Metrics/ClassLength:
22
+ Max: 1500
23
+
24
+ # No space makes the method definition shorter and differentiates
25
+ # from a regular assignment.
26
+ Layout/SpaceAroundEqualsInParameterDefault:
27
+ EnforcedStyle: no_space
28
+
29
+ # We do not need to support Ruby 1.9, so this is good to use.
30
+ Style/SymbolArray:
31
+ Enabled: true
32
+
33
+ # Most readable form.
34
+ Style/OptionHash:
35
+ EnforcedHashRocketStyle: table
36
+ EnforcedColonStyle: table
37
+
38
+ # Mixing the styles looks just silly.
39
+ Style/HashSyntax:
40
+ EnforcedStyle: ruby19_no_mixed_keys
41
+
42
+ # has_key? and has_value? are far more readable than key? and value?
43
+ Style/PreferredHashMethods:
44
+ Enabled: false
45
+
46
+ # String#% is by far the least verbose and only object oriented variant.
47
+ Style/FormatString:
48
+ EnforcedStyle: percent
49
+
50
+ Style/CollectionMethods:
51
+ Enabled: true
52
+ PreferredMethods:
53
+ # inject seems more common in the community.
54
+ reduce: "inject"
55
+
56
+
57
+ # Either allow this style or don't. Marking it as safe with parenthesis
58
+ # is silly. Let's try to live without them for now.
59
+ Style/ParenthesesAroundCondition:
60
+ AllowSafeAssignment: false
61
+ Lint/AssignmentInCondition:
62
+ AllowSafeAssignment: false
63
+
64
+ # A specialized exception class will take one or more arguments and construct the message from it.
65
+ # So both variants make sense.
66
+ Style/RaiseArgs:
67
+ Enabled: false
68
+
69
+ # Indenting the chained dots beneath each other is not supported by this cop,
70
+ # see https://github.com/bbatsov/rubocop/issues/1633
71
+ Layout/MultilineOperationIndentation:
72
+ Enabled: false
73
+
74
+ # Fail is an alias of raise. Avoid aliases, it's more cognitive load for no gain.
75
+ # The argument that fail should be used to abort the program is wrong too,
76
+ # there's Kernel#abort for that.
77
+ Style/SignalException:
78
+ EnforcedStyle: only_raise
79
+
80
+ # Suppressing exceptions can be perfectly fine, and be it to avoid to
81
+ # explicitly type nil into the rescue since that's what you want to return,
82
+ # or suppressing LoadError for optional dependencies
83
+ Lint/SuppressedException:
84
+ Enabled: false
85
+
86
+ #Layout/SpaceInsideBlockBraces:
87
+ # # The space here provides no real gain in readability while consuming
88
+ # # horizontal space that could be used for a better parameter name.
89
+ # # Also {| differentiates better from a hash than { | does.
90
+ # SpaceBeforeBlockParameters: false
91
+
92
+ # No trailing space differentiates better from the block:
93
+ # foo} means hash, foo } means block.
94
+ Layout/SpaceInsideHashLiteralBraces:
95
+ EnforcedStyle: no_space
96
+
97
+ # { ... } for multi-line blocks is okay, follow Weirichs rule instead:
98
+ # https://web.archive.org/web/20140221124509/http://onestepback.org/index.cgi/Tech/Ruby/BraceVsDoEnd.rdoc
99
+ Style/BlockDelimiters:
100
+ Enabled: false
101
+
102
+ # do / end blocks should be used for side effects,
103
+ # methods that run a block for side effects and have
104
+ # a useful return value are rare, assign the return
105
+ # value to a local variable for those cases.
106
+ Style/MethodCalledOnDoEndBlock:
107
+ Enabled: true
108
+
109
+ # Enforcing the names of variables? To single letter ones? Just no.
110
+ Style/SingleLineBlockParams:
111
+ Enabled: false
112
+
113
+ # Shadowing outer local variables with block parameters is often useful
114
+ # to not reinvent a new name for the same thing, it highlights the relation
115
+ # between the outer variable and the parameter. The cases where it's actually
116
+ # confusing are rare, and usually bad for other reasons already, for example
117
+ # because the method is too long.
118
+ Lint/ShadowingOuterLocalVariable:
119
+ Enabled: false
120
+
121
+ # Check with yard instead.
122
+ Style/Documentation:
123
+ Enabled: false
124
+
125
+ # There are valid cases, for example debugging Cucumber steps,
126
+ # also they'll fail CI anyway
127
+ Lint/Debugger:
128
+ Enabled: false
129
+
130
+ # Style preference
131
+ Style/MethodDefParentheses:
132
+ Enabled: false
@@ -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 me@williamthom.as. 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/Dockerfile ADDED
@@ -0,0 +1,10 @@
1
+ FROM ruby:3.0.2
2
+ RUN apt-get update && apt-get install -y \
3
+ build-essential
4
+
5
+ RUN mkdir /app
6
+ WORKDIR /app
7
+ COPY . .
8
+ RUN gem install bundler && bundle install --jobs 20 --retry 5
9
+ RUN rake install
10
+ CMD ["bash"]
data/Gemfile ADDED
@@ -0,0 +1,12 @@
1
+ # frozen_string_literal: true
2
+
3
+ source "https://rubygems.org"
4
+
5
+ # Specify your gem's dependencies in cure.gemspec
6
+ gemspec
7
+
8
+ gem "rake", "~> 13.0"
9
+
10
+ gem "rspec", "~> 3.0"
11
+
12
+ gem "rubocop", "~> 1.21"
data/Gemfile.lock ADDED
@@ -0,0 +1,71 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ cure (0.1.1)
5
+ faker
6
+ rcsv
7
+
8
+ GEM
9
+ remote: https://rubygems.org/
10
+ specs:
11
+ ast (2.4.2)
12
+ concurrent-ruby (1.1.10)
13
+ diff-lcs (1.4.4)
14
+ docile (1.4.0)
15
+ faker (2.21.0)
16
+ i18n (>= 1.8.11, < 2)
17
+ i18n (1.10.0)
18
+ concurrent-ruby (~> 1.0)
19
+ parallel (1.21.0)
20
+ parser (3.0.2.0)
21
+ ast (~> 2.4.1)
22
+ rainbow (3.0.0)
23
+ rake (13.0.6)
24
+ rcsv (0.3.1)
25
+ regexp_parser (2.1.1)
26
+ rexml (3.2.5)
27
+ rspec (3.10.0)
28
+ rspec-core (~> 3.10.0)
29
+ rspec-expectations (~> 3.10.0)
30
+ rspec-mocks (~> 3.10.0)
31
+ rspec-core (3.10.1)
32
+ rspec-support (~> 3.10.0)
33
+ rspec-expectations (3.10.1)
34
+ diff-lcs (>= 1.2.0, < 2.0)
35
+ rspec-support (~> 3.10.0)
36
+ rspec-mocks (3.10.2)
37
+ diff-lcs (>= 1.2.0, < 2.0)
38
+ rspec-support (~> 3.10.0)
39
+ rspec-support (3.10.3)
40
+ rubocop (1.22.3)
41
+ parallel (~> 1.10)
42
+ parser (>= 3.0.0.0)
43
+ rainbow (>= 2.2.2, < 4.0)
44
+ regexp_parser (>= 1.8, < 3.0)
45
+ rexml
46
+ rubocop-ast (>= 1.12.0, < 2.0)
47
+ ruby-progressbar (~> 1.7)
48
+ unicode-display_width (>= 1.4.0, < 3.0)
49
+ rubocop-ast (1.13.0)
50
+ parser (>= 3.0.1.1)
51
+ ruby-progressbar (1.11.0)
52
+ simplecov (0.21.2)
53
+ docile (~> 1.1)
54
+ simplecov-html (~> 0.11)
55
+ simplecov_json_formatter (~> 0.1)
56
+ simplecov-html (0.12.3)
57
+ simplecov_json_formatter (0.1.4)
58
+ unicode-display_width (2.1.0)
59
+
60
+ PLATFORMS
61
+ x86_64-linux
62
+
63
+ DEPENDENCIES
64
+ cure!
65
+ rake (~> 13.0)
66
+ rspec (~> 3.0)
67
+ rubocop (~> 1.21)
68
+ simplecov
69
+
70
+ BUNDLED WITH
71
+ 2.3.13
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 william
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,129 @@
1
+ # Cure
2
+
3
+ ![run tests](https://github.com/williamthom-as/cure/actions/workflows/rspec.yml/badge.svg)
4
+
5
+ Cure is a simple tool to **remove/redact/anonymize** and **replace** private information in a spreadsheet.
6
+ It has been written to anonymize private cloud billing data for use in public demo environments.
7
+
8
+ It has several key features:
9
+ - Define either full or regex match groups replacements.
10
+ - Choose from many strategies to replace anonymous data - random number sequences, GUIDs, placeholders, multipliers amongst many others.
11
+ - **Existing generated values are stored and recalled** so once a replacement is defined, it is kept around for other columns to use.
12
+ - For example, once a replacement **Account Number** is generated, any further use of that number sequence is other columns will be used, keeping data real(ish) and functional in a relational sense.
13
+
14
+ ## Use Cases
15
+
16
+ - Strip out personal data from a CSV that may be used for public demo.
17
+
18
+ ## Usage
19
+
20
+ Cure requires two things, a **template** (or rules) file. This is a descriptive file that provides the translations required on each column.
21
+ A candidate column entry provides the translations to be run on each column.
22
+
23
+ Please see example below.
24
+ ```json
25
+ {
26
+ "column" : "identity/LineItemId",
27
+ "translations" : [{
28
+ "strategy" : {
29
+ "name": "full",
30
+ "options" : {}
31
+ },
32
+ "generator" : {
33
+ "name" : "character",
34
+ "options" : {
35
+ "length" : 52,
36
+ "types" : [
37
+ "lowercase", "number", "uppercase"
38
+ ]
39
+ }
40
+ }
41
+ }]
42
+ }
43
+ ```
44
+
45
+ A **translation** is made up of a strategy and generator.
46
+
47
+ **Strategies** are the means of selecting the *value* to change. You may choose from:
48
+ - **Full replacement**: replaces the full entry.
49
+ - **Regex replacement**: can replace either the match group (partial), or full record *if* there is a match.
50
+ - **Includes replacement**: can replace either the matched substring, or full record *if* there is a match.
51
+ - **StartWith replacement**: can replace either the starts with substring, or full record *if* there is a match.
52
+ - **EndWith replacement**: can replace either the end with substring, or full record *if* there is a match.
53
+
54
+ **Generators** are the way a replacement value is generated. You may choose from:
55
+ - Random number generator
56
+ - Random Hex numbers
57
+ - Random character strings
58
+ - Placeholder lookups
59
+ - Redaction strings
60
+ - Removal (empty string)
61
+
62
+ ## Example
63
+
64
+ ```json
65
+ {
66
+ "column" : "identity/ResourceId",
67
+ "translations" : [{
68
+ "strategy" : {
69
+ "name": "full",
70
+ "options" : {}
71
+ },
72
+ "generator" : {
73
+ "name" : "character",
74
+ "options" : {
75
+ "length" : 10,
76
+ "types" : [
77
+ "lowercase", "number"
78
+ ]
79
+ }
80
+ }
81
+ }]
82
+ }
83
+ ```
84
+
85
+ The above example would translate a source value from column **identity/ResourceId** as follows:
86
+
87
+ i-ae44e104ef1 => ddsf78ds56
88
+
89
+ # A full replacement, with a random generated 10 character string
90
+ # made up of lowercase letters and numbers
91
+
92
+ You can see more of these examples in the Examples folder.
93
+
94
+ ## Installation
95
+
96
+ Install it yourself as:
97
+
98
+ $ gem install cure
99
+
100
+ ### Getting started *quickly*
101
+
102
+ To quickly spin up a development environment, please use the Dockerfile provided. Run:
103
+
104
+ $ docker build -t cure .
105
+ $ docker run -it --rm cure bash
106
+
107
+ Please do not forget to mount any volumes which may have templates that you wish to use. Default templates are available too, found under `/app/templates`.
108
+
109
+ Once set up and connected to your container, run:
110
+
111
+ $ cure -t /file/path/to/template.json -s /file/path/to/source_file.csv -o /my/output/folder
112
+
113
+ ## Development
114
+
115
+ 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.
116
+
117
+ 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).
118
+
119
+ ## Contributing
120
+
121
+ Bug reports and pull requests are welcome on GitHub at https://github.com/williamthom-as/cure. 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]/cure/blob/master/CODE_OF_CONDUCT.md).
122
+
123
+ ## License
124
+
125
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
126
+
127
+ ## Code of Conduct
128
+
129
+ Everyone interacting in the Cure project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/[USERNAME]/cure/blob/master/CODE_OF_CONDUCT.md).
data/Rakefile ADDED
@@ -0,0 +1,12 @@
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
11
+
12
+ task default: %i[spec rubocop]
data/exe/cure ADDED
@@ -0,0 +1,42 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "cure"
5
+ require "optparse"
6
+
7
+ include Cure::Log
8
+
9
+ class CureConfig
10
+ include Cure::Configuration
11
+ end
12
+
13
+ conf = {}
14
+
15
+ OptionParser.new do |opts|
16
+ opts.banner = "Usage: cure_cli [options]"
17
+
18
+ opts.on("-t", "--template_file=template_file", "Template definition file") do |t|
19
+ conf[:template_file_location] = t
20
+ end
21
+
22
+ opts.on("-s", "--source_file=source_file", "Source file") do |s|
23
+ conf[:source_file_location] = s
24
+ end
25
+
26
+ opts.on("-o", "--output_dir=output_dir", "Output directory") do |o|
27
+ conf[:output_dir] = o
28
+ end
29
+
30
+ opts.on("-h", "--help", "Prints this help") do
31
+ puts opts
32
+ exit
33
+ end
34
+ end.parse!
35
+
36
+ log_info "Config loaded successfully, initialising environment ..."
37
+ main = Cure::Main.init(conf[:template_file_location], conf[:source_file_location], conf[:output_dir])
38
+
39
+ log_info "... set up complete. Beginning process"
40
+ main.process
41
+
42
+
@@ -0,0 +1,56 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cure"
4
+ require "json"
5
+ require "singleton"
6
+
7
+ module Cure
8
+ module Configuration
9
+ # @return [Config]
10
+ def config
11
+ conf = ConfigurationSource.instance.config
12
+ raise "Set config first" unless conf
13
+
14
+ conf
15
+ end
16
+
17
+ # @param [Config] request_config
18
+ def register_config(request_config)
19
+ ConfigurationSource.instance.load_config(request_config)
20
+ end
21
+
22
+ # @return [Config]
23
+ def create_config(source_file_location, template, output_dir)
24
+ Config.new(source_file_location, template, output_dir)
25
+ end
26
+
27
+ class Config
28
+ attr_accessor :source_file_location, :template, :output_dir
29
+
30
+ # @param [String] source_file_location
31
+ # @param [Hash] template
32
+ # @param [String] output_dir
33
+ def initialize(source_file_location, template, output_dir)
34
+ @source_file_location = source_file_location
35
+ @template = template
36
+ @output_dir = output_dir
37
+ end
38
+
39
+ def placeholders
40
+ @template["placeholders"] || []
41
+ end
42
+ end
43
+
44
+ class ConfigurationSource
45
+ include Singleton
46
+
47
+ attr_reader :config
48
+
49
+ # @param [Config] config
50
+ # @return [Config]
51
+ def load_config(config)
52
+ @config = config
53
+ end
54
+ end
55
+ end
56
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Cure
4
+ module CSVHelpers
5
+ end
6
+ end
@@ -0,0 +1,49 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "cure/log"
4
+ require "cure/file_helpers"
5
+
6
+ module Cure
7
+ module Export
8
+ class Exporter
9
+ include Cure::FileHelpers
10
+ include Log
11
+
12
+ def self.export_ctx(ctx, output_dir, file_name)
13
+ column_headers = ctx.column_headers.keys
14
+
15
+ exporter = Exporter.new
16
+ exporter.export(output_dir, file_name, ctx.transformed_rows, column_headers)
17
+ end
18
+
19
+ # @param [Array] rows
20
+ # @param [Array] columns
21
+ def export(output_dir, file_name, rows, columns)
22
+ log_info("Exporting file to [#{output_dir}/#{file_name}] with #{rows.length} rows")
23
+
24
+ file_contents = []
25
+ file_contents << columns.join(",")
26
+
27
+ rows.each do |row|
28
+ file_contents << row.join(",")
29
+ end
30
+
31
+ write_to_file(
32
+ output_dir, file_name, "csv", file_contents.join("\n")
33
+ )
34
+ end
35
+
36
+ # @param [String] file_path
37
+ # @param [String] contents
38
+ # @param [String] file_extension
39
+ def write_to_file(file_path, file_name, file_extension, contents)
40
+ file_location = "#{file_path}/#{file_name || Time.now.utc.strftime("%Y-%m-%dT%H:%M:%S%-z")}"
41
+ clean_dir(file_path)
42
+
43
+ with_file(file_location, file_extension) do |file|
44
+ file.write(contents)
45
+ end
46
+ end
47
+ end
48
+ end
49
+ end
@@ -0,0 +1,38 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "fileutils"
4
+
5
+ module Cure
6
+ module FileHelpers
7
+ def with_file(path, extension, &block)
8
+ dir = File.dirname(path)
9
+
10
+ FileUtils.mkdir_p(dir) unless File.directory?(dir)
11
+
12
+ path = "#{path}.#{extension}"
13
+ File.open(path, "w", &block)
14
+ end
15
+
16
+ def clean_dir(path)
17
+ dir = File.file?(path) ? File.dirname(path) : path
18
+
19
+ FileUtils.remove_dir(dir) if File.directory?(dir)
20
+ end
21
+
22
+ def read_file(file_location)
23
+ result = file_location.start_with?("/") ? file_location : File.join(File.dirname(__FILE__), file_location)
24
+
25
+ raise "No file found at [#{file_location}]" unless File.exist? result
26
+
27
+ File.read(result)
28
+ end
29
+
30
+ def with_temp_dir(temp_dir, &_block)
31
+ return unless block_given?
32
+
33
+ clean_dir(temp_dir)
34
+ yield
35
+ clean_dir(temp_dir)
36
+ end
37
+ end
38
+ end