infer_model 0.1.0
Sign up to get free protection for your applications and to get access to all the features.
- checksums.yaml +7 -0
- data/.rubocop.yml +105 -0
- data/.ruby-version +1 -0
- data/CHANGELOG.md +5 -0
- data/CODE_OF_CONDUCT.md +84 -0
- data/Gemfile +8 -0
- data/Gemfile.lock +86 -0
- data/LICENSE.txt +21 -0
- data/README.md +89 -0
- data/Rakefile +12 -0
- data/infer_model.gemspec +47 -0
- data/lib/infer_model/callable.rb +6 -0
- data/lib/infer_model/common_type.rb +15 -0
- data/lib/infer_model/common_type_guesser.rb +44 -0
- data/lib/infer_model/from/csv.rb +41 -0
- data/lib/infer_model/from.rb +4 -0
- data/lib/infer_model/model.rb +10 -0
- data/lib/infer_model/parsers/boolean.rb +24 -0
- data/lib/infer_model/parsers/date_time.rb +39 -0
- data/lib/infer_model/parsers/decimal.rb +20 -0
- data/lib/infer_model/parsers/integer.rb +21 -0
- data/lib/infer_model/parsers/json.rb +22 -0
- data/lib/infer_model/parsers/time.rb +28 -0
- data/lib/infer_model/parsers/uuid.rb +21 -0
- data/lib/infer_model/parsers.rb +18 -0
- data/lib/infer_model/task.rb +38 -0
- data/lib/infer_model/to/migration.rb +67 -0
- data/lib/infer_model/to/text.rb +50 -0
- data/lib/infer_model/to.rb +4 -0
- data/lib/infer_model/value_type_guesser.rb +56 -0
- data/lib/infer_model/version.rb +5 -0
- data/lib/infer_model.rb +20 -0
- data/sig/infer_model.rbs +4 -0
- metadata +194 -0
checksums.yaml
ADDED
@@ -0,0 +1,7 @@
|
|
1
|
+
---
|
2
|
+
SHA256:
|
3
|
+
metadata.gz: beae3b14bb858f6f8d597788daa62d18ab9246d4ccc81e8d862f08b5e6bcf99f
|
4
|
+
data.tar.gz: 9856dc12362b8f109260e272b2a392d61a3a54c22f02085ffe3146d35acd5ebf
|
5
|
+
SHA512:
|
6
|
+
metadata.gz: 49929b9598e50253e0eff456bd7a73894d782d95fb82fe90f5dd5c73bcd13eb2a59b4cb86da983b735b236652d9944f10370c35d6dd60265e0183f007cb0a177
|
7
|
+
data.tar.gz: 61c7a94a1f691dad8f6e3999cfcb876472e92c0ca4bf566f1e33d9d567d5835531a97743425317900fa0067664deaeab5ea244e5f3101c13b46ab338b9e8ac3f
|
data/.rubocop.yml
ADDED
@@ -0,0 +1,105 @@
|
|
1
|
+
require:
|
2
|
+
- 'rubocop-performance'
|
3
|
+
|
4
|
+
AllCops:
|
5
|
+
Exclude:
|
6
|
+
- bin/**/* # Let gems do their stuff
|
7
|
+
- vendor/bundle/**/* # Let gems do their stuff
|
8
|
+
- .pryrc # Do what you want here
|
9
|
+
- tmp/**/* # Do what you want here
|
10
|
+
- doc/**/*
|
11
|
+
- node_modules/**/*
|
12
|
+
NewCops: enable
|
13
|
+
|
14
|
+
###
|
15
|
+
|
16
|
+
# Disable or configure cops with reasons:
|
17
|
+
|
18
|
+
Layout/LineLength:
|
19
|
+
Enabled: false # Disabled as it would require heavy refactoring in most codebases. Feel free to enable it for your project!
|
20
|
+
|
21
|
+
# Alignment-cops. Settings aim to avoid deep indentations and diff noise.
|
22
|
+
Layout/FirstArgumentIndentation:
|
23
|
+
EnforcedStyle: consistent
|
24
|
+
Layout/FirstArrayElementIndentation:
|
25
|
+
EnforcedStyle: consistent
|
26
|
+
Layout/FirstHashElementIndentation:
|
27
|
+
EnforcedStyle: consistent
|
28
|
+
Layout/MultilineMethodCallIndentation:
|
29
|
+
EnforcedStyle: indented
|
30
|
+
Layout/ArgumentAlignment:
|
31
|
+
EnforcedStyle: with_fixed_indentation
|
32
|
+
Layout/CaseIndentation:
|
33
|
+
EnforcedStyle: end
|
34
|
+
Layout/EndAlignment:
|
35
|
+
EnforcedStyleAlignWith: start_of_line
|
36
|
+
|
37
|
+
Layout/EmptyLineAfterGuardClause:
|
38
|
+
Enabled: false # Methods should be short anyway, so that a guard clause will be visible enough without an empty line
|
39
|
+
|
40
|
+
Style/ClassAndModuleChildren: # Each version has its own benefits depending on the situation
|
41
|
+
Enabled: false
|
42
|
+
Style/Documentation: # We currently do not enforce documentation. Do it where you feel it is useful!
|
43
|
+
Enabled: false
|
44
|
+
Style/EmptyMethod: # Do not allow `def foo; end` for empty methods as semicolons are discouraged in ruby
|
45
|
+
EnforcedStyle: expanded
|
46
|
+
Style/FrozenStringLiteralComment: # Might be enabled in the future
|
47
|
+
Enabled: false
|
48
|
+
Style/Lambda: # Always use `->` instead of `lambda`, as the latter does not work with `do ... end` and we do not want to use `{ ... }` for multiline-blocks (see https://github.com/rubocop-hq/rubocop/issues/1520)
|
49
|
+
EnforcedStyle: literal
|
50
|
+
Style/NumericPredicate: # Sometimes "== 0" is easier to read than .zero?
|
51
|
+
Enabled: false
|
52
|
+
Style/StringLiterals:
|
53
|
+
EnforcedStyle: double_quotes # Avoids having to change quotes when adding interpolation to a string.
|
54
|
+
Style/StringLiteralsInInterpolation:
|
55
|
+
EnforcedStyle: double_quotes
|
56
|
+
Style/TrailingCommaInArguments:
|
57
|
+
EnforcedStyleForMultiline: consistent_comma # Makes it easier to swap lines and avoids noise in diffs
|
58
|
+
Style/TrailingCommaInArrayLiteral:
|
59
|
+
EnforcedStyleForMultiline: consistent_comma # Makes it easier to swap lines and avoids noise in diffs
|
60
|
+
Style/TrailingCommaInHashLiteral:
|
61
|
+
EnforcedStyleForMultiline: consistent_comma # Makes it easier to swap lines and avoids noise in diffs
|
62
|
+
|
63
|
+
###
|
64
|
+
|
65
|
+
# Tune metrics cops
|
66
|
+
|
67
|
+
# Background: metrics cops, although they are sometimes annoying, give you a stimulus to think about the complexity of the code.
|
68
|
+
# So, while it is true that good code style is best ensured by peer review, pair programming or ensemble (mob) programming, it's
|
69
|
+
# good that the metrics cops have your back and act as a last line of defense while you are wrapping your head around other
|
70
|
+
# aspects. Therefore we soften the default limits, so that the cops are not too whiny and annoy the developers, but we keep them
|
71
|
+
# enabled.
|
72
|
+
# Recommendation: if you offend a metrics cop for good reason, disable that specific cop in the offending file only (see
|
73
|
+
# https://docs.rubocop.org/rubocop/configuration.html#disabling-cops-within-source-code). See also the README next to this file.
|
74
|
+
|
75
|
+
# Length metrics
|
76
|
+
Metrics/ClassLength:
|
77
|
+
Max: 200 # 2 times of the default value of 100, above this you should really think about splitting up the class
|
78
|
+
Metrics/ModuleLength:
|
79
|
+
Max: 200 # 2 times of the default value of 100, above this you should really think about splitting up the module
|
80
|
+
Metrics/MethodLength:
|
81
|
+
Max: 30 # 3 times of the default value of 10, above this you should really think about splitting up the method
|
82
|
+
CountAsOne: ['array', 'heredoc', 'hash'] # Do not incentivise against multi-line and in-method constants and declarative programming
|
83
|
+
Exclude:
|
84
|
+
- db/migrate/**/* # let migrations do what they need
|
85
|
+
Metrics/BlockLength: # the default value of 25 is good
|
86
|
+
Exclude:
|
87
|
+
- config/**/* # There is no reason to artificially break up config blocks
|
88
|
+
- lib/tasks/**/*.rake
|
89
|
+
- spec/**/* # describe or context blocks may be large
|
90
|
+
- '*.gemspec'
|
91
|
+
|
92
|
+
# Method signature complexity metrics
|
93
|
+
Metrics/ParameterLists:
|
94
|
+
Max: 3 # more than 3 positional parameters get confusing, use keyword args or group input parameters in value objects instead
|
95
|
+
CountKeywordArgs: false # keyword args are OK, they are way more readable than positional args
|
96
|
+
|
97
|
+
# Code complexity metrics
|
98
|
+
Metrics/AbcSize:
|
99
|
+
Max: 43 # ~2.5 times of the default value of 17, above this your method is most likely too complex
|
100
|
+
Metrics/CyclomaticComplexity:
|
101
|
+
Max: 14 # 2 times of the default value of 7, above this your method is most likely too complex
|
102
|
+
Metrics/PerceivedComplexity:
|
103
|
+
Max: 12 # 1.5 times of the default value of 8, above this your method is most likely too complex
|
104
|
+
|
105
|
+
###
|
data/.ruby-version
ADDED
@@ -0,0 +1 @@
|
|
1
|
+
3.1.2
|
data/CHANGELOG.md
ADDED
data/CODE_OF_CONDUCT.md
ADDED
@@ -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 jay.schneider@zweitag.de. 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
data/Gemfile.lock
ADDED
@@ -0,0 +1,86 @@
|
|
1
|
+
PATH
|
2
|
+
remote: .
|
3
|
+
specs:
|
4
|
+
infer_model (0.1.0)
|
5
|
+
activesupport (~> 7.0)
|
6
|
+
dry-initializer (~> 3.0)
|
7
|
+
zeitwerk (~> 2.6)
|
8
|
+
|
9
|
+
GEM
|
10
|
+
remote: https://rubygems.org/
|
11
|
+
specs:
|
12
|
+
activesupport (7.0.3.1)
|
13
|
+
concurrent-ruby (~> 1.0, >= 1.0.2)
|
14
|
+
i18n (>= 1.6, < 2)
|
15
|
+
minitest (>= 5.1)
|
16
|
+
tzinfo (~> 2.0)
|
17
|
+
ast (2.4.2)
|
18
|
+
coderay (1.1.3)
|
19
|
+
concurrent-ruby (1.1.10)
|
20
|
+
diff-lcs (1.5.0)
|
21
|
+
dotenv (2.8.1)
|
22
|
+
dry-initializer (3.1.1)
|
23
|
+
i18n (1.12.0)
|
24
|
+
concurrent-ruby (~> 1.0)
|
25
|
+
json (2.6.2)
|
26
|
+
method_source (1.0.0)
|
27
|
+
minitest (5.16.3)
|
28
|
+
parallel (1.22.1)
|
29
|
+
parser (3.1.2.1)
|
30
|
+
ast (~> 2.4.1)
|
31
|
+
pry (0.14.1)
|
32
|
+
coderay (~> 1.1)
|
33
|
+
method_source (~> 1.0)
|
34
|
+
rainbow (3.1.1)
|
35
|
+
rake (13.0.6)
|
36
|
+
regexp_parser (2.5.0)
|
37
|
+
rexml (3.2.5)
|
38
|
+
rspec (3.11.0)
|
39
|
+
rspec-core (~> 3.11.0)
|
40
|
+
rspec-expectations (~> 3.11.0)
|
41
|
+
rspec-mocks (~> 3.11.0)
|
42
|
+
rspec-core (3.11.0)
|
43
|
+
rspec-support (~> 3.11.0)
|
44
|
+
rspec-expectations (3.11.0)
|
45
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
46
|
+
rspec-support (~> 3.11.0)
|
47
|
+
rspec-mocks (3.11.1)
|
48
|
+
diff-lcs (>= 1.2.0, < 2.0)
|
49
|
+
rspec-support (~> 3.11.0)
|
50
|
+
rspec-support (3.11.0)
|
51
|
+
rubocop (1.36.0)
|
52
|
+
json (~> 2.3)
|
53
|
+
parallel (~> 1.10)
|
54
|
+
parser (>= 3.1.2.1)
|
55
|
+
rainbow (>= 2.2.2, < 4.0)
|
56
|
+
regexp_parser (>= 1.8, < 3.0)
|
57
|
+
rexml (>= 3.2.5, < 4.0)
|
58
|
+
rubocop-ast (>= 1.20.1, < 2.0)
|
59
|
+
ruby-progressbar (~> 1.7)
|
60
|
+
unicode-display_width (>= 1.4.0, < 3.0)
|
61
|
+
rubocop-ast (1.21.0)
|
62
|
+
parser (>= 3.1.1.0)
|
63
|
+
rubocop-performance (1.14.3)
|
64
|
+
rubocop (>= 1.7.0, < 2.0)
|
65
|
+
rubocop-ast (>= 0.4.0)
|
66
|
+
ruby-progressbar (1.11.0)
|
67
|
+
tzinfo (2.0.5)
|
68
|
+
concurrent-ruby (~> 1.0)
|
69
|
+
unicode-display_width (2.2.0)
|
70
|
+
zeitwerk (2.6.0)
|
71
|
+
|
72
|
+
PLATFORMS
|
73
|
+
arm64-darwin-21
|
74
|
+
x86_64-linux
|
75
|
+
|
76
|
+
DEPENDENCIES
|
77
|
+
dotenv (~> 2.8)
|
78
|
+
infer_model!
|
79
|
+
pry (~> 0.14)
|
80
|
+
rake
|
81
|
+
rspec (~> 3.11)
|
82
|
+
rubocop (~> 1.36)
|
83
|
+
rubocop-performance (~> 1.14)
|
84
|
+
|
85
|
+
BUNDLED WITH
|
86
|
+
2.3.17
|
data/LICENSE.txt
ADDED
@@ -0,0 +1,21 @@
|
|
1
|
+
The MIT License (MIT)
|
2
|
+
|
3
|
+
Copyright (c) 2022 Jay Schneider
|
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,89 @@
|
|
1
|
+
[![Continuous Integration](https://github.com/Jay-Schneider/infer_model/actions/workflows/ci.yml/badge.svg)](https://github.com/Jay-Schneider/infer_model/actions/workflows/ci.yml)
|
2
|
+
|
3
|
+
# InferModel
|
4
|
+
|
5
|
+
Infer a model from data.
|
6
|
+
|
7
|
+
This gem transforms data dumps into managable structures.
|
8
|
+
|
9
|
+
You can use it to deduce certain properties from a given set of data to use it to build a database around this data.
|
10
|
+
|
11
|
+
The main use case is:
|
12
|
+
Given a csv file that was exported from some tool, you want to manage and process the contained data in a database, say in your rails application.
|
13
|
+
It would be valid to create a string column for every CSV column and import the data as is but you lose a lot of information by doing so.
|
14
|
+
|
15
|
+
Instead what this tool allows you to do is to guess which data type, like integer, decimal, boolean, etc, is the best fit for each column and allows you to create migrations or scripts to do so almost automatically.
|
16
|
+
|
17
|
+
Additionally the values may be parsed to deduce further features of your data that may be useful when setting up a database, like uniqueness or non-null constraints.
|
18
|
+
|
19
|
+
## Installation
|
20
|
+
|
21
|
+
Install the gem and add to the application's Gemfile by executing:
|
22
|
+
|
23
|
+
$ bundle add infer_model
|
24
|
+
|
25
|
+
If bundler is not being used to manage dependencies, install the gem by executing:
|
26
|
+
|
27
|
+
$ gem install infer_model
|
28
|
+
|
29
|
+
## Usage
|
30
|
+
|
31
|
+
A CLI is yet to be written. But you may run the tool from inside your code or an interactive session.
|
32
|
+
|
33
|
+
### Inferring information from data
|
34
|
+
|
35
|
+
Run code like the following:
|
36
|
+
|
37
|
+
```ruby
|
38
|
+
require "infer_model"
|
39
|
+
|
40
|
+
# Just display the results in a human readable format
|
41
|
+
InferModel.from(:csv, "path/to/file.csv").to(:text).call
|
42
|
+
|
43
|
+
# Create a rails migration for me with the inferred information
|
44
|
+
InferModel.from(:csv, "path/to/file.csv", csv_options: { col_sep: ";", encoding: "csp1252" }).to(:migration, rails_version: "6.0", table_name: "csv_contents").call
|
45
|
+
```
|
46
|
+
|
47
|
+
More "Adapters" that can be used as `from` source or `to` target may be added in the future. If you have ideas or needs please contribute by creating an issue or pr.
|
48
|
+
|
49
|
+
### Importing data
|
50
|
+
|
51
|
+
After generating a database table fitting to your data, you might want to fill them. You can use `InferModel`s parsers to do so. For example in your rails app, in an import service or seeds:
|
52
|
+
|
53
|
+
```ruby
|
54
|
+
now = Time.current
|
55
|
+
column_types = MyModel.columns.to_h { |column| [column.name, column.type] }
|
56
|
+
|
57
|
+
data = ::CSV.foreach("my_model_data.csv", col_sep: ";", encoding: "utf-8", headers: true, header_converters: :symbol).map do |row|
|
58
|
+
parsed_attributes = row.to_h.to_h do |column_name, value| # note the `to_h.to_h`: The first one turns the row into a hash, the second one allows building a new hash with the block. CSV::Row's #to_h method does not process the block properly.
|
59
|
+
column_type = column_types.fetch(column_name.to_s)
|
60
|
+
parser = InferModel::Parsers::BY_TYPE.fetch(column_type)
|
61
|
+
[column_name, parser.call(value)]
|
62
|
+
end
|
63
|
+
{ created_at: now, updated_at: now }.merge(parsed_attributes)
|
64
|
+
end
|
65
|
+
|
66
|
+
MyModel.upsert_all(data) if data.present? # rubocop:disable Rails/SkipsModelValidations
|
67
|
+
```
|
68
|
+
|
69
|
+
That way you profit from the parsers logic that already generated your tables. For example the `Boolean` parser acknowledges `"Y"` as a _truthy_ value compared to `"N"` which is considered _falsey_. When you use a different parser or just attempt to insert the string value into your database, they will most likely all have `true` as value in the corresponding column just because `"N"` is considered truthy.
|
70
|
+
|
71
|
+
For more information on how different parsers work, have a look inside their definition, e.g. the constants `InferModel::Parsers::Boolean::TRUTHY_VALUES_LOWERCASE` and `FALSEY_VALUES_LOWERCASE`. There might be the option to configure those values in the future.
|
72
|
+
|
73
|
+
## Development
|
74
|
+
|
75
|
+
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.
|
76
|
+
|
77
|
+
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).
|
78
|
+
|
79
|
+
## Contributing
|
80
|
+
|
81
|
+
Bug reports and pull requests are welcome on GitHub at https://github.com/Jay-Schneider/infer_model. 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/Jay-Schneider/infer_model/blob/main/CODE_OF_CONDUCT.md).
|
82
|
+
|
83
|
+
## License
|
84
|
+
|
85
|
+
The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
|
86
|
+
|
87
|
+
## Code of Conduct
|
88
|
+
|
89
|
+
Everyone interacting in the InferModel project's codebases, issue trackers, chat rooms and mailing lists is expected to follow the [code of conduct](https://github.com/Jay-Schneider/infer_model/blob/main/CODE_OF_CONDUCT.md).
|
data/Rakefile
ADDED
data/infer_model.gemspec
ADDED
@@ -0,0 +1,47 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require_relative "lib/infer_model/version"
|
4
|
+
|
5
|
+
Gem::Specification.new do |spec|
|
6
|
+
spec.name = "infer_model"
|
7
|
+
spec.version = InferModel::VERSION
|
8
|
+
spec.authors = ["Jay Schneider"]
|
9
|
+
spec.email = ["jay.schneider@zweitag.de"]
|
10
|
+
|
11
|
+
spec.summary = "Infer data types from external sources to create a rails model for example"
|
12
|
+
spec.description = "This gem tries to detect the data type from given data like a csv file. You can then use this information to generate a rails migration to have a fitting model for the data."
|
13
|
+
spec.homepage = "https://github.com/Jay-Schneider/infer_model"
|
14
|
+
spec.license = "MIT"
|
15
|
+
spec.required_ruby_version = ">= 3.1.0"
|
16
|
+
|
17
|
+
spec.metadata = {
|
18
|
+
"bug_tracker_uri" => "https://github.com/Jay-Schneider/infer_model/issues",
|
19
|
+
"changelog_uri" => "https://github.com/Jay-Schneider/infer_model/CHANGELOG.md",
|
20
|
+
"homepage_uri" => spec.homepage,
|
21
|
+
"rubygems_mfa_required" => "true",
|
22
|
+
"source_code_uri" => "https://github.com/Jay-Schneider/infer_model",
|
23
|
+
}
|
24
|
+
|
25
|
+
# Specify which files should be added to the gem when it is released.
|
26
|
+
# The `git ls-files -z` loads the files in the RubyGem that have been added into git.
|
27
|
+
spec.files = Dir.chdir(__dir__) do
|
28
|
+
`git ls-files -z`.split("\x0").reject do |f|
|
29
|
+
(f == __FILE__) || f.match(%r{\A(?:(?:bin|test|spec|features)/|\.(?:git|travis|circleci)|appveyor)})
|
30
|
+
end
|
31
|
+
end
|
32
|
+
spec.bindir = "bin"
|
33
|
+
spec.executables = spec.files.grep(%r{\Abin/}) { |f| File.basename(f) }
|
34
|
+
spec.require_paths = ["lib"]
|
35
|
+
|
36
|
+
spec.add_dependency "activesupport", "~> 7.0"
|
37
|
+
spec.add_dependency "dry-initializer", "~> 3.0"
|
38
|
+
spec.add_dependency "zeitwerk", "~> 2.6"
|
39
|
+
spec.add_development_dependency "dotenv", "~> 2.8"
|
40
|
+
spec.add_development_dependency "pry", "~> 0.14"
|
41
|
+
spec.add_development_dependency "rspec", "~> 3.11"
|
42
|
+
spec.add_development_dependency "rubocop", "~> 1.36"
|
43
|
+
spec.add_development_dependency "rubocop-performance", "~> 1.14"
|
44
|
+
|
45
|
+
# For more information and examples about making a new gem, check out our
|
46
|
+
# guide at: https://bundler.io/guides/creating_gem.html
|
47
|
+
end
|
@@ -0,0 +1,15 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class CommonType
|
5
|
+
extend Dry::Initializer
|
6
|
+
|
7
|
+
param :possible_detected_types
|
8
|
+
option :unique_constraint_possible, default: -> { false }
|
9
|
+
option :non_null_constraint_possible, default: -> { false }
|
10
|
+
|
11
|
+
def detected_type
|
12
|
+
possible_detected_types.respond_to?(:first) ? possible_detected_types.first : possible_detected_types
|
13
|
+
end
|
14
|
+
end
|
15
|
+
end
|
@@ -0,0 +1,44 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class CommonTypeGuesser
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
param :inputs
|
9
|
+
option :available_types, default: -> { ValueTypeGuesser::RESULT_TYPES }
|
10
|
+
option :multi, default: -> { false }
|
11
|
+
option :allow_blank, default: -> { true }
|
12
|
+
option :detect_uniqueness, default: -> { true }
|
13
|
+
option :detect_non_null, default: -> { true }
|
14
|
+
|
15
|
+
def call
|
16
|
+
inputs.each do |input|
|
17
|
+
@available_types = ValueTypeGuesser.call(input, allow_blank:, available_types:, multi: true)
|
18
|
+
end
|
19
|
+
possible_detected_types = multi ? available_types : available_types.first
|
20
|
+
|
21
|
+
@parsed_inputs = inputs.map { Parsers::BY_TYPE.fetch(available_types.first).call(_1) }
|
22
|
+
|
23
|
+
CommonType.new(
|
24
|
+
possible_detected_types,
|
25
|
+
unique_constraint_possible:,
|
26
|
+
non_null_constraint_possible:,
|
27
|
+
)
|
28
|
+
end
|
29
|
+
|
30
|
+
private
|
31
|
+
|
32
|
+
def unique_constraint_possible
|
33
|
+
return unless detect_uniqueness
|
34
|
+
|
35
|
+
@parsed_inputs.size == @parsed_inputs.uniq.size
|
36
|
+
end
|
37
|
+
|
38
|
+
def non_null_constraint_possible
|
39
|
+
return unless detect_non_null
|
40
|
+
|
41
|
+
@parsed_inputs.none?(&:nil?)
|
42
|
+
end
|
43
|
+
end
|
44
|
+
end
|
@@ -0,0 +1,41 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_support/core_ext/hash/reverse_merge"
|
4
|
+
require "csv"
|
5
|
+
|
6
|
+
module InferModel::From
|
7
|
+
class CSV
|
8
|
+
extend Dry::Initializer
|
9
|
+
extend InferModel::Callable
|
10
|
+
|
11
|
+
DEFAULT_CSV_OPTIONS = { col_sep: ",", encoding: "utf-8", headers: true, quote_char: "\x00" }.freeze
|
12
|
+
|
13
|
+
param :filename
|
14
|
+
option :available_types, default: -> { ::InferModel::ValueTypeGuesser::RESULT_TYPES }
|
15
|
+
option :multi, default: -> { false }
|
16
|
+
option :csv_options, default: -> { {} }
|
17
|
+
|
18
|
+
def call
|
19
|
+
::InferModel::Model.new(source_name:, attributes:)
|
20
|
+
end
|
21
|
+
|
22
|
+
private
|
23
|
+
|
24
|
+
def source_name = File.basename(filename, File.extname(filename))
|
25
|
+
|
26
|
+
def attributes
|
27
|
+
csv.by_col!.to_h do |header, contents|
|
28
|
+
[
|
29
|
+
header.downcase.to_sym,
|
30
|
+
::InferModel::CommonTypeGuesser.call(contents, available_types:),
|
31
|
+
]
|
32
|
+
end
|
33
|
+
end
|
34
|
+
|
35
|
+
def csv = ::CSV.parse(file_content, **csv_options_with_defaults)
|
36
|
+
|
37
|
+
def file_content = File.read(filename)
|
38
|
+
|
39
|
+
def csv_options_with_defaults = csv_options.with_defaults(DEFAULT_CSV_OPTIONS)
|
40
|
+
end
|
41
|
+
end
|
@@ -0,0 +1,24 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class Parsers::Boolean
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
param :value
|
9
|
+
option :allow_blank, default: -> { true }
|
10
|
+
|
11
|
+
TRUTHY_VALUES_LOWERCASE = %w[true t x y j + * 1].freeze
|
12
|
+
FALSEY_VALUES_LOWERCASE = %w[false f n - 0].freeze
|
13
|
+
|
14
|
+
def call
|
15
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
16
|
+
return if value.nil?
|
17
|
+
return false if value.empty?
|
18
|
+
return false if FALSEY_VALUES_LOWERCASE.any? { |lie| value.casecmp(lie).zero? }
|
19
|
+
return true if TRUTHY_VALUES_LOWERCASE.any? { |truth| value.casecmp(truth).zero? }
|
20
|
+
|
21
|
+
raise Parsers::Error, "'#{value}' is not a Boolean"
|
22
|
+
end
|
23
|
+
end
|
24
|
+
end
|
@@ -0,0 +1,39 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "date"
|
4
|
+
|
5
|
+
module InferModel
|
6
|
+
class Parsers::DateTime
|
7
|
+
extend Callable
|
8
|
+
extend Dry::Initializer
|
9
|
+
|
10
|
+
ACCEPTABLE_DATETIME_FORMATS = [
|
11
|
+
"%Y-%m-%dT%T%z",
|
12
|
+
"%Y-%m-%dT%T%Z",
|
13
|
+
"%Y-%m-%dT%TZ",
|
14
|
+
"%d.%m.%Y %T%z",
|
15
|
+
"%d.%m.%Y %T%Z",
|
16
|
+
"%d.%m.%Y %T",
|
17
|
+
"%d.%m.%Y %H:%M",
|
18
|
+
"%Y-%m-%dT",
|
19
|
+
"%Y-%m-%d",
|
20
|
+
"%d.%m.%Y",
|
21
|
+
].freeze
|
22
|
+
|
23
|
+
param :value
|
24
|
+
option :allow_blank, default: -> { true }
|
25
|
+
|
26
|
+
def call
|
27
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
28
|
+
return if value.nil? || value.empty?
|
29
|
+
|
30
|
+
ACCEPTABLE_DATETIME_FORMATS.each do |format|
|
31
|
+
return DateTime.strptime(value, format)
|
32
|
+
rescue Date::Error
|
33
|
+
next
|
34
|
+
end
|
35
|
+
|
36
|
+
raise Parsers::Error, "'#{value}' is not a DateTime"
|
37
|
+
end
|
38
|
+
end
|
39
|
+
end
|
@@ -0,0 +1,20 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class Parsers::Decimal
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
param :value
|
9
|
+
option :allow_blank, default: -> { true }
|
10
|
+
|
11
|
+
def call
|
12
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
13
|
+
return if value.nil? || value.empty?
|
14
|
+
|
15
|
+
Float(value)
|
16
|
+
rescue ArgumentError
|
17
|
+
raise Parsers::Error, "'#{value}' is not a Decimal"
|
18
|
+
end
|
19
|
+
end
|
20
|
+
end
|
@@ -0,0 +1,21 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class Parsers::Integer
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
param :value
|
9
|
+
option :allow_blank, default: -> { true }
|
10
|
+
option :base, default: -> { 10 }
|
11
|
+
|
12
|
+
def call
|
13
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
14
|
+
return if value.nil? || value.empty?
|
15
|
+
|
16
|
+
Integer(value, base)
|
17
|
+
rescue ArgumentError
|
18
|
+
raise Parsers::Error, "'#{value}' is not an Integer"
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
@@ -0,0 +1,22 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "json"
|
4
|
+
|
5
|
+
module InferModel
|
6
|
+
class Parsers::JSON
|
7
|
+
extend Callable
|
8
|
+
extend Dry::Initializer
|
9
|
+
|
10
|
+
param :value
|
11
|
+
option :allow_blank, default: -> { true }
|
12
|
+
|
13
|
+
def call
|
14
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
15
|
+
return if value.nil? || value.empty?
|
16
|
+
|
17
|
+
JSON.parse(value)
|
18
|
+
rescue JSON::ParserError
|
19
|
+
raise Parsers::Error, "'#{value}' is not a JSON"
|
20
|
+
end
|
21
|
+
end
|
22
|
+
end
|
@@ -0,0 +1,28 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "time"
|
4
|
+
|
5
|
+
module InferModel
|
6
|
+
class Parsers::Time
|
7
|
+
extend Callable
|
8
|
+
extend Dry::Initializer
|
9
|
+
|
10
|
+
ACCEPTABLE_TIME_FORMATS = %w[%T %R].freeze
|
11
|
+
|
12
|
+
param :value
|
13
|
+
option :allow_blank, default: -> { true }
|
14
|
+
|
15
|
+
def call
|
16
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
17
|
+
return if value.nil? || value.empty?
|
18
|
+
|
19
|
+
ACCEPTABLE_TIME_FORMATS.each do |format|
|
20
|
+
return Time.strptime(value, format)
|
21
|
+
rescue ArgumentError
|
22
|
+
next
|
23
|
+
end
|
24
|
+
|
25
|
+
raise Parsers::Error, "'#{value}' is not a Time"
|
26
|
+
end
|
27
|
+
end
|
28
|
+
end
|
@@ -0,0 +1,21 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class Parsers::UUID
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
UUID_REGEX = /\A[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\z/i
|
9
|
+
|
10
|
+
param :value
|
11
|
+
option :allow_blank, default: -> { true }
|
12
|
+
|
13
|
+
def call
|
14
|
+
raise Parsers::Error, "value was blank which is not allowed" if value.nil? && !allow_blank
|
15
|
+
return if value.nil? || value.empty?
|
16
|
+
return value if UUID_REGEX.match?(value)
|
17
|
+
|
18
|
+
raise Parsers::Error, "'#{value}' is not a UUID"
|
19
|
+
end
|
20
|
+
end
|
21
|
+
end
|
@@ -0,0 +1,18 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
module Parsers
|
5
|
+
Error = Class.new(StandardError)
|
6
|
+
|
7
|
+
BY_TYPE = {
|
8
|
+
boolean: Boolean,
|
9
|
+
datetime: DateTime,
|
10
|
+
decimal: Decimal,
|
11
|
+
integer: Integer,
|
12
|
+
json: JSON,
|
13
|
+
time: Time,
|
14
|
+
uuid: UUID,
|
15
|
+
string: ->(*args, **_opts) { args[0] },
|
16
|
+
}.freeze
|
17
|
+
end
|
18
|
+
end
|
@@ -0,0 +1,38 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class Task
|
5
|
+
FROMS = { csv: ::InferModel::From::CSV }.freeze
|
6
|
+
TOS = {
|
7
|
+
migration: ::InferModel::To::Migration,
|
8
|
+
text: ::InferModel::To::Text,
|
9
|
+
}.freeze
|
10
|
+
|
11
|
+
attr_reader :from_object, :from_args, :from_opts, :to_object, :to_args, :to_opts
|
12
|
+
|
13
|
+
def from(from_object, *args, **opts)
|
14
|
+
@from_object = from_object
|
15
|
+
@from_object = FROMS.fetch(from_object) if FROMS.key?(from_object)
|
16
|
+
@from_args = args
|
17
|
+
@from_opts = opts
|
18
|
+
self
|
19
|
+
end
|
20
|
+
|
21
|
+
def to(to_object, *args, **opts)
|
22
|
+
@to_object = to_object
|
23
|
+
@to_object = TOS.fetch(to_object) if TOS.key?(to_object)
|
24
|
+
@to_args = args
|
25
|
+
@to_opts = opts
|
26
|
+
self
|
27
|
+
end
|
28
|
+
|
29
|
+
def call
|
30
|
+
to_object.call(from_object.call(*from_args, **from_opts), *to_args, **to_opts)
|
31
|
+
end
|
32
|
+
|
33
|
+
class << self
|
34
|
+
def from(...) = new.from(...)
|
35
|
+
def to(...) = new.to(...)
|
36
|
+
end
|
37
|
+
end
|
38
|
+
end
|
@@ -0,0 +1,67 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
require "active_support/core_ext/string/inflections"
|
4
|
+
|
5
|
+
module InferModel::To
|
6
|
+
class Migration
|
7
|
+
extend Dry::Initializer
|
8
|
+
extend InferModel::Callable
|
9
|
+
|
10
|
+
TIMESTAMP_FORMAT = "%Y%m%d%H%M%S"
|
11
|
+
|
12
|
+
param :model
|
13
|
+
option :target_dir, default: -> { "db/migrate" }
|
14
|
+
option :table_name, optional: true
|
15
|
+
option :rails_version, default: -> { "7.0" }
|
16
|
+
|
17
|
+
def call
|
18
|
+
FileUtils.mkdir_p(target_dir)
|
19
|
+
File.write(migration_filename, migration_content)
|
20
|
+
end
|
21
|
+
|
22
|
+
private
|
23
|
+
|
24
|
+
def migration_filename
|
25
|
+
timestamp = Time.now.localtime.strftime(TIMESTAMP_FORMAT)
|
26
|
+
File.join(target_dir, "#{timestamp}_create_#{given_or_inferred_tablename}.rb")
|
27
|
+
end
|
28
|
+
|
29
|
+
def given_or_inferred_tablename
|
30
|
+
table_name || model.source_name.pluralize
|
31
|
+
end
|
32
|
+
|
33
|
+
def migration_content
|
34
|
+
<<~RUBY
|
35
|
+
# frozen_string_literal: true
|
36
|
+
|
37
|
+
class Create#{given_or_inferred_tablename.camelize} < ActiveRecord::Migration[#{rails_version}]
|
38
|
+
def change
|
39
|
+
create_table "#{given_or_inferred_tablename}" do |t|
|
40
|
+
#{column_ddl_lines}
|
41
|
+
|
42
|
+
t.timestamps
|
43
|
+
end
|
44
|
+
end
|
45
|
+
end
|
46
|
+
RUBY
|
47
|
+
end
|
48
|
+
|
49
|
+
COLUMN_DDL_LINES_WITH_INDENTATION_JOINER = "\n#{" " * 3}".freeze
|
50
|
+
|
51
|
+
def column_ddl_lines
|
52
|
+
column_definitions = model.attributes.map do |key, common_type|
|
53
|
+
attribute_and_name = %(t.#{common_type.detected_type} "#{key}")
|
54
|
+
non_null_constraint = common_type.non_null_constraint_possible ? "null: false" : nil
|
55
|
+
|
56
|
+
[attribute_and_name, non_null_constraint].compact.join(", ")
|
57
|
+
end
|
58
|
+
index_definitions = model.attributes.filter_map do |key, common_type|
|
59
|
+
next unless common_type.unique_constraint_possible
|
60
|
+
|
61
|
+
%(t.index ["#{key}"], unique: true)
|
62
|
+
end
|
63
|
+
|
64
|
+
(column_definitions + index_definitions).join(COLUMN_DDL_LINES_WITH_INDENTATION_JOINER)
|
65
|
+
end
|
66
|
+
end
|
67
|
+
end
|
@@ -0,0 +1,50 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel::To
|
4
|
+
class Text
|
5
|
+
extend Dry::Initializer
|
6
|
+
extend InferModel::Callable
|
7
|
+
|
8
|
+
param :model
|
9
|
+
option :outstream, default: -> { $stdout }
|
10
|
+
|
11
|
+
def call
|
12
|
+
outstream << <<~TEXT
|
13
|
+
#{title}
|
14
|
+
#{formatted_attributes.join("\n\n")}
|
15
|
+
TEXT
|
16
|
+
end
|
17
|
+
|
18
|
+
private
|
19
|
+
|
20
|
+
def title
|
21
|
+
source_name_line = "Source Name: '#{model.source_name}'"
|
22
|
+
<<~TEXT
|
23
|
+
#{source_name_line}
|
24
|
+
#{"#" * source_name_line.size}
|
25
|
+
|
26
|
+
Attributes:
|
27
|
+
-----------
|
28
|
+
TEXT
|
29
|
+
end
|
30
|
+
|
31
|
+
def formatted_attributes
|
32
|
+
model.attributes.map do |attr_name, common_type|
|
33
|
+
formatted_attribute(attr_name, common_type)
|
34
|
+
end
|
35
|
+
end
|
36
|
+
|
37
|
+
def formatted_attribute(attr_name, common_type)
|
38
|
+
attr_____string = "#{attr_name}:"
|
39
|
+
type_____string = " Type: #{common_type.detected_type}"
|
40
|
+
unique___string = " Unique: contains only unique values" if common_type.unique_constraint_possible
|
41
|
+
non_null_string = " Non null: does not contain empty values" if common_type.non_null_constraint_possible
|
42
|
+
[
|
43
|
+
attr_____string,
|
44
|
+
type_____string,
|
45
|
+
unique___string,
|
46
|
+
non_null_string,
|
47
|
+
].compact.join("\n")
|
48
|
+
end
|
49
|
+
end
|
50
|
+
end
|
@@ -0,0 +1,56 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
module InferModel
|
4
|
+
class ValueTypeGuesser
|
5
|
+
extend Callable
|
6
|
+
extend Dry::Initializer
|
7
|
+
|
8
|
+
param :input
|
9
|
+
option :available_types, default: -> { RESULT_TYPES }
|
10
|
+
option :multi, default: -> { false }
|
11
|
+
option :allow_blank, default: -> { true }
|
12
|
+
|
13
|
+
INTEGER_RESULT = :integer # bigint included
|
14
|
+
DECIMAL_RESULT = :decimal # float included
|
15
|
+
DATETIME_RESULT = :datetime # date included
|
16
|
+
TIME_RESULT = :time
|
17
|
+
BOOLEAN_RESULT = :boolean
|
18
|
+
JSON_RESULT = :json
|
19
|
+
UUID_RESULT = :uuid
|
20
|
+
STRING_RESULT = :string # text included
|
21
|
+
RESULT_TYPES = [ # ordered by specifity (string should come last, integer before decimal etc.)
|
22
|
+
INTEGER_RESULT,
|
23
|
+
DECIMAL_RESULT,
|
24
|
+
BOOLEAN_RESULT,
|
25
|
+
TIME_RESULT,
|
26
|
+
DATETIME_RESULT,
|
27
|
+
JSON_RESULT,
|
28
|
+
UUID_RESULT,
|
29
|
+
STRING_RESULT,
|
30
|
+
].freeze
|
31
|
+
|
32
|
+
def call
|
33
|
+
raise Error, "Provide strings only for guessing the type" unless input.is_a?(String) || input.nil?
|
34
|
+
if multi
|
35
|
+
ordered_available_known_types.filter { |type| may_be?(type) }
|
36
|
+
else
|
37
|
+
ordered_available_known_types.find { |type| may_be?(type) }
|
38
|
+
end
|
39
|
+
end
|
40
|
+
|
41
|
+
private
|
42
|
+
|
43
|
+
def ordered_available_known_types
|
44
|
+
RESULT_TYPES & available_types
|
45
|
+
end
|
46
|
+
|
47
|
+
def may_be?(type)
|
48
|
+
type = type.to_s.downcase.to_sym
|
49
|
+
raise ArgumentError, "unknown type '#{type}'" unless InferModel::Parsers::BY_TYPE.key?(type)
|
50
|
+
|
51
|
+
InferModel::Parsers::BY_TYPE.fetch(type).call(input, allow_blank:) || true # false is allowed for boolean
|
52
|
+
rescue Parsers::Error
|
53
|
+
false
|
54
|
+
end
|
55
|
+
end
|
56
|
+
end
|
data/lib/infer_model.rb
ADDED
@@ -0,0 +1,20 @@
|
|
1
|
+
# frozen_string_literal: true
|
2
|
+
|
3
|
+
# libraries
|
4
|
+
require "dotenv/load"
|
5
|
+
require "dry-initializer"
|
6
|
+
require "pry"
|
7
|
+
require "zeitwerk"
|
8
|
+
|
9
|
+
loader = Zeitwerk::Loader.for_gem
|
10
|
+
loader.inflector.inflect("csv" => "CSV", "json" => "JSON", "uuid" => "UUID")
|
11
|
+
loader.setup
|
12
|
+
|
13
|
+
module InferModel
|
14
|
+
class Error < StandardError; end
|
15
|
+
|
16
|
+
class << self
|
17
|
+
def from(...) = Task.from(...)
|
18
|
+
def to(...) = Task.to(...)
|
19
|
+
end
|
20
|
+
end
|
data/sig/infer_model.rbs
ADDED
metadata
ADDED
@@ -0,0 +1,194 @@
|
|
1
|
+
--- !ruby/object:Gem::Specification
|
2
|
+
name: infer_model
|
3
|
+
version: !ruby/object:Gem::Version
|
4
|
+
version: 0.1.0
|
5
|
+
platform: ruby
|
6
|
+
authors:
|
7
|
+
- Jay Schneider
|
8
|
+
autorequire:
|
9
|
+
bindir: bin
|
10
|
+
cert_chain: []
|
11
|
+
date: 2022-09-10 00:00:00.000000000 Z
|
12
|
+
dependencies:
|
13
|
+
- !ruby/object:Gem::Dependency
|
14
|
+
name: activesupport
|
15
|
+
requirement: !ruby/object:Gem::Requirement
|
16
|
+
requirements:
|
17
|
+
- - "~>"
|
18
|
+
- !ruby/object:Gem::Version
|
19
|
+
version: '7.0'
|
20
|
+
type: :runtime
|
21
|
+
prerelease: false
|
22
|
+
version_requirements: !ruby/object:Gem::Requirement
|
23
|
+
requirements:
|
24
|
+
- - "~>"
|
25
|
+
- !ruby/object:Gem::Version
|
26
|
+
version: '7.0'
|
27
|
+
- !ruby/object:Gem::Dependency
|
28
|
+
name: dry-initializer
|
29
|
+
requirement: !ruby/object:Gem::Requirement
|
30
|
+
requirements:
|
31
|
+
- - "~>"
|
32
|
+
- !ruby/object:Gem::Version
|
33
|
+
version: '3.0'
|
34
|
+
type: :runtime
|
35
|
+
prerelease: false
|
36
|
+
version_requirements: !ruby/object:Gem::Requirement
|
37
|
+
requirements:
|
38
|
+
- - "~>"
|
39
|
+
- !ruby/object:Gem::Version
|
40
|
+
version: '3.0'
|
41
|
+
- !ruby/object:Gem::Dependency
|
42
|
+
name: zeitwerk
|
43
|
+
requirement: !ruby/object:Gem::Requirement
|
44
|
+
requirements:
|
45
|
+
- - "~>"
|
46
|
+
- !ruby/object:Gem::Version
|
47
|
+
version: '2.6'
|
48
|
+
type: :runtime
|
49
|
+
prerelease: false
|
50
|
+
version_requirements: !ruby/object:Gem::Requirement
|
51
|
+
requirements:
|
52
|
+
- - "~>"
|
53
|
+
- !ruby/object:Gem::Version
|
54
|
+
version: '2.6'
|
55
|
+
- !ruby/object:Gem::Dependency
|
56
|
+
name: dotenv
|
57
|
+
requirement: !ruby/object:Gem::Requirement
|
58
|
+
requirements:
|
59
|
+
- - "~>"
|
60
|
+
- !ruby/object:Gem::Version
|
61
|
+
version: '2.8'
|
62
|
+
type: :development
|
63
|
+
prerelease: false
|
64
|
+
version_requirements: !ruby/object:Gem::Requirement
|
65
|
+
requirements:
|
66
|
+
- - "~>"
|
67
|
+
- !ruby/object:Gem::Version
|
68
|
+
version: '2.8'
|
69
|
+
- !ruby/object:Gem::Dependency
|
70
|
+
name: pry
|
71
|
+
requirement: !ruby/object:Gem::Requirement
|
72
|
+
requirements:
|
73
|
+
- - "~>"
|
74
|
+
- !ruby/object:Gem::Version
|
75
|
+
version: '0.14'
|
76
|
+
type: :development
|
77
|
+
prerelease: false
|
78
|
+
version_requirements: !ruby/object:Gem::Requirement
|
79
|
+
requirements:
|
80
|
+
- - "~>"
|
81
|
+
- !ruby/object:Gem::Version
|
82
|
+
version: '0.14'
|
83
|
+
- !ruby/object:Gem::Dependency
|
84
|
+
name: rspec
|
85
|
+
requirement: !ruby/object:Gem::Requirement
|
86
|
+
requirements:
|
87
|
+
- - "~>"
|
88
|
+
- !ruby/object:Gem::Version
|
89
|
+
version: '3.11'
|
90
|
+
type: :development
|
91
|
+
prerelease: false
|
92
|
+
version_requirements: !ruby/object:Gem::Requirement
|
93
|
+
requirements:
|
94
|
+
- - "~>"
|
95
|
+
- !ruby/object:Gem::Version
|
96
|
+
version: '3.11'
|
97
|
+
- !ruby/object:Gem::Dependency
|
98
|
+
name: rubocop
|
99
|
+
requirement: !ruby/object:Gem::Requirement
|
100
|
+
requirements:
|
101
|
+
- - "~>"
|
102
|
+
- !ruby/object:Gem::Version
|
103
|
+
version: '1.36'
|
104
|
+
type: :development
|
105
|
+
prerelease: false
|
106
|
+
version_requirements: !ruby/object:Gem::Requirement
|
107
|
+
requirements:
|
108
|
+
- - "~>"
|
109
|
+
- !ruby/object:Gem::Version
|
110
|
+
version: '1.36'
|
111
|
+
- !ruby/object:Gem::Dependency
|
112
|
+
name: rubocop-performance
|
113
|
+
requirement: !ruby/object:Gem::Requirement
|
114
|
+
requirements:
|
115
|
+
- - "~>"
|
116
|
+
- !ruby/object:Gem::Version
|
117
|
+
version: '1.14'
|
118
|
+
type: :development
|
119
|
+
prerelease: false
|
120
|
+
version_requirements: !ruby/object:Gem::Requirement
|
121
|
+
requirements:
|
122
|
+
- - "~>"
|
123
|
+
- !ruby/object:Gem::Version
|
124
|
+
version: '1.14'
|
125
|
+
description: This gem tries to detect the data type from given data like a csv file.
|
126
|
+
You can then use this information to generate a rails migration to have a fitting
|
127
|
+
model for the data.
|
128
|
+
email:
|
129
|
+
- jay.schneider@zweitag.de
|
130
|
+
executables: []
|
131
|
+
extensions: []
|
132
|
+
extra_rdoc_files: []
|
133
|
+
files:
|
134
|
+
- ".rubocop.yml"
|
135
|
+
- ".ruby-version"
|
136
|
+
- CHANGELOG.md
|
137
|
+
- CODE_OF_CONDUCT.md
|
138
|
+
- Gemfile
|
139
|
+
- Gemfile.lock
|
140
|
+
- LICENSE.txt
|
141
|
+
- README.md
|
142
|
+
- Rakefile
|
143
|
+
- infer_model.gemspec
|
144
|
+
- lib/infer_model.rb
|
145
|
+
- lib/infer_model/callable.rb
|
146
|
+
- lib/infer_model/common_type.rb
|
147
|
+
- lib/infer_model/common_type_guesser.rb
|
148
|
+
- lib/infer_model/from.rb
|
149
|
+
- lib/infer_model/from/csv.rb
|
150
|
+
- lib/infer_model/model.rb
|
151
|
+
- lib/infer_model/parsers.rb
|
152
|
+
- lib/infer_model/parsers/boolean.rb
|
153
|
+
- lib/infer_model/parsers/date_time.rb
|
154
|
+
- lib/infer_model/parsers/decimal.rb
|
155
|
+
- lib/infer_model/parsers/integer.rb
|
156
|
+
- lib/infer_model/parsers/json.rb
|
157
|
+
- lib/infer_model/parsers/time.rb
|
158
|
+
- lib/infer_model/parsers/uuid.rb
|
159
|
+
- lib/infer_model/task.rb
|
160
|
+
- lib/infer_model/to.rb
|
161
|
+
- lib/infer_model/to/migration.rb
|
162
|
+
- lib/infer_model/to/text.rb
|
163
|
+
- lib/infer_model/value_type_guesser.rb
|
164
|
+
- lib/infer_model/version.rb
|
165
|
+
- sig/infer_model.rbs
|
166
|
+
homepage: https://github.com/Jay-Schneider/infer_model
|
167
|
+
licenses:
|
168
|
+
- MIT
|
169
|
+
metadata:
|
170
|
+
bug_tracker_uri: https://github.com/Jay-Schneider/infer_model/issues
|
171
|
+
changelog_uri: https://github.com/Jay-Schneider/infer_model/CHANGELOG.md
|
172
|
+
homepage_uri: https://github.com/Jay-Schneider/infer_model
|
173
|
+
rubygems_mfa_required: 'true'
|
174
|
+
source_code_uri: https://github.com/Jay-Schneider/infer_model
|
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: 3.1.0
|
184
|
+
required_rubygems_version: !ruby/object:Gem::Requirement
|
185
|
+
requirements:
|
186
|
+
- - ">="
|
187
|
+
- !ruby/object:Gem::Version
|
188
|
+
version: '0'
|
189
|
+
requirements: []
|
190
|
+
rubygems_version: 3.3.7
|
191
|
+
signing_key:
|
192
|
+
specification_version: 4
|
193
|
+
summary: Infer data types from external sources to create a rails model for example
|
194
|
+
test_files: []
|