generated_schema_validations 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
+ SHA256:
3
+ metadata.gz: 977b8c39503dc3cabfad86bc011240a877dfb84c49d12d4f9fe7f643426bbbc0
4
+ data.tar.gz: 5a6ab82e347f48f6bb7ff5c0308bbfeec6b9f20414967036a0149d2e56592224
5
+ SHA512:
6
+ metadata.gz: 06345f91aaa7aa5a8d3b797a80bb70c55e58450aad7e1abf38c136373b3c7db3ed184bcc91ca7ba43f88611628e468700d6c909f30f2b9b06a5aa99749d84c85
7
+ data.tar.gz: e2ff2c3ed55bb9aa6af514f1ccdb19dc80eb0b098de3c2a141d00cd85cdb3ff01717f6986038619d0048c31b9519a348aff090f3785e725dcc61dc4f7350bd1e
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/Gemfile ADDED
@@ -0,0 +1,9 @@
1
+ # frozen_string_literal: true
2
+
3
+ source 'https://rubygems.org'
4
+
5
+ # Specify your gem's dependencies in generated_schema_validations.gemspec
6
+ gemspec
7
+
8
+ gem 'rake', '~> 12.0'
9
+ gem 'rspec', '~> 3.0'
data/Gemfile.lock ADDED
@@ -0,0 +1,34 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ generated_schema_validations (0.1.0)
5
+
6
+ GEM
7
+ remote: https://rubygems.org/
8
+ specs:
9
+ diff-lcs (1.4.4)
10
+ rake (12.3.3)
11
+ rspec (3.10.0)
12
+ rspec-core (~> 3.10.0)
13
+ rspec-expectations (~> 3.10.0)
14
+ rspec-mocks (~> 3.10.0)
15
+ rspec-core (3.10.1)
16
+ rspec-support (~> 3.10.0)
17
+ rspec-expectations (3.10.1)
18
+ diff-lcs (>= 1.2.0, < 2.0)
19
+ rspec-support (~> 3.10.0)
20
+ rspec-mocks (3.10.2)
21
+ diff-lcs (>= 1.2.0, < 2.0)
22
+ rspec-support (~> 3.10.0)
23
+ rspec-support (3.10.3)
24
+
25
+ PLATFORMS
26
+ ruby
27
+
28
+ DEPENDENCIES
29
+ generated_schema_validations!
30
+ rake (~> 12.0)
31
+ rspec (~> 3.0)
32
+
33
+ BUNDLED WITH
34
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Georg Limbach
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,103 @@
1
+ # GeneratedSchemaValidations
2
+
3
+ This Gem helps to transfer the defaults from the database schema to the rails validations. To do this, it uses the information in schema.rb and transfers it to a concern file. This file should be included in the version control.
4
+
5
+ ## Installation
6
+
7
+ Add this line to your application's Gemfile:
8
+
9
+ ```ruby
10
+ gem 'generated_schema_validations'
11
+ ```
12
+
13
+ And then execute:
14
+
15
+ $ bundle install
16
+
17
+ Or install it yourself as:
18
+
19
+ $ gem install generated_schema_validations
20
+
21
+
22
+ ### Generate concern file
23
+
24
+ To generate `app/models/concerns/schema_validations.rb`:
25
+
26
+ $ rails db:migrate
27
+
28
+ ### Use validations
29
+
30
+ Add to `app/mode/application_record.rb`:
31
+
32
+ ```ruby
33
+ class ApplicationRecord < ActiveRecord::Base
34
+ self.abstract_class = true
35
+ include SchemaValidations # to include auto generated validations
36
+ end
37
+ ```
38
+
39
+ Use it in a model **after** you defined the associations:
40
+
41
+ ```ruby
42
+ class User < ApplicationRecord
43
+ belongs_to :client
44
+ belongs_to :other
45
+
46
+ validate :email_address, email_format: true
47
+
48
+ schema_validations # to use auto generated validations
49
+
50
+ def stuff; end
51
+ end
52
+ ```
53
+
54
+ ### Exclude from rubocp and simplecov
55
+
56
+ Add to simplecov config file (e.g. `.simplecov`):
57
+
58
+ ```
59
+ add_filter '/app/models/concerns/schema_validations.rb'
60
+ ```
61
+
62
+ Add to rubocop config file (e. g. `config/rubocop.rb`):
63
+
64
+ ```
65
+ AllCops:
66
+ Exclude:
67
+ - app/models/concerns/schema_validations.rb
68
+ ```
69
+
70
+
71
+ ## Usage
72
+
73
+ Every time you change schema.rb file with rake tasks `db:schema:dump` the generated file `schema_validations.rb` will fresh created. The task `db:migrate` use intern `db:schema:dump`.
74
+
75
+ It is hardcoded, that this will only run on development environment.
76
+
77
+
78
+ ## How it works
79
+
80
+ ```ruby
81
+ t.text :stuff, null: false
82
+ # results in
83
+ validate :stuff, presence: true
84
+
85
+ t.string :stuff, limit: 10
86
+ # results in
87
+ validate :stuff, length: { maximum: 10 }
88
+
89
+ t.integer :stuff
90
+ # results in
91
+ validate :stuff, numericality: true
92
+ ```
93
+
94
+ You can watch changes on `schema_validations.rb` to understand the generated validations.
95
+
96
+ ## Contributing
97
+
98
+ Bug reports and pull requests are welcome on GitHub at https://github.com/Lichtbit/generated_schema_validations.
99
+
100
+
101
+ ## License
102
+
103
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'bundler/gem_tasks'
4
+ require 'rspec/core/rake_task'
5
+
6
+ RSpec::Core::RakeTask.new(:spec)
7
+
8
+ task default: :spec
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'generated_schema_validations'
5
+ spec.version = '0.1.0'
6
+ spec.authors = ['Georg Limbach']
7
+ spec.email = ['georg.limbach@lichtbit.com']
8
+
9
+ spec.summary = 'Generate rails validations from schema.rb file'
10
+ spec.description = 'After each migration it generates a file with some validations. Each active record should ' \
11
+ 'include this file and can uns generated validations.'
12
+ spec.homepage = 'https://github.com/Lichtbit/generated_schema_validations'
13
+ spec.license = 'MIT'
14
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
15
+
16
+ spec.metadata['homepage_uri'] = spec.homepage
17
+ spec.metadata['source_code_uri'] = 'https://github.com/Lichtbit/generated_schema_validations'
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.require_paths = ['lib']
25
+ end
@@ -0,0 +1,48 @@
1
+ # frozen_string_literal: true
2
+
3
+ class GeneratedSchemaValidations::Dumper
4
+ def self.generate
5
+ return unless Rails.env.development?
6
+
7
+ file = Tempfile.new(['schema', '.rb'])
8
+ begin
9
+ schema_content = File.read(Rails.root.join('db/schema.rb'))
10
+ schema_content.gsub!('ActiveRecord::Schema', 'GeneratedSchemaValidations::Dumper')
11
+ raise 'The scheme is not well-formed.' if schema_content.include?('ActiveRecord')
12
+
13
+ file.write(schema_content)
14
+
15
+ load file.path
16
+ ensure
17
+ file.close
18
+ file.unlink
19
+ end
20
+ end
21
+
22
+ def self.define(info = {}, &block)
23
+ new.define(info, &block)
24
+ end
25
+
26
+ def define(info, &block)
27
+ instance_eval(&block)
28
+
29
+ template_ruby = File.read(File.expand_path('template.rb', File.dirname(__FILE__)))
30
+ template_ruby.gsub!('VERSION_INFO', info[:version].to_s)
31
+ indention_spaces = template_ruby.match(/( +)TABLE_VALIDATIONS/)[1]
32
+ table_validations_ruby = @table_validations_ruby.lines.map do |line|
33
+ line.strip.present? ? "#{indention_spaces}#{line}" : "\n"
34
+ end.join
35
+ template_ruby.gsub!("#{indention_spaces}TABLE_VALIDATIONS", table_validations_ruby)
36
+
37
+ File.write(Rails.root.join('app/models/concerns/schema_validations.rb'), template_ruby)
38
+ end
39
+
40
+ def create_table(table_name, *, &block)
41
+ @table_validations_ruby ||= ''
42
+ @table_validations_ruby += GeneratedSchemaValidations::Table.new(table_name, &block).to_s
43
+ end
44
+
45
+ def do_nothing(*); end
46
+ alias enable_extension do_nothing
47
+ alias add_foreign_key do_nothing
48
+ end
@@ -0,0 +1,10 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'generated_schema_validations'
4
+ require 'rails'
5
+
6
+ class GeneratedSchemaValidations::Railtie < Rails::Railtie
7
+ rake_tasks do
8
+ load 'generated_schema_validations/tasks.rb'
9
+ end
10
+ end
@@ -0,0 +1,128 @@
1
+ # frozen_string_literal: true
2
+
3
+ class GeneratedSchemaValidations::Table
4
+ Validation = Struct.new(:attribute, :validator, :options) do
5
+ def to_s
6
+ "validates_with_filter #{attribute.to_sym.inspect}, #{{ validator => options }.inspect}"
7
+ end
8
+ end
9
+
10
+ attr_reader :table_name
11
+
12
+ def initialize(table_name, &block)
13
+ @table_name = table_name
14
+ @column_names = []
15
+ @possible_belongs_to_not_null_columns = []
16
+ @unique_indexes = []
17
+ @validations = []
18
+
19
+ instance_eval(&block)
20
+ end
21
+
22
+ def to_s
23
+ string = "\n"
24
+ string += "def dbv_#{table_name}_validations\n"
25
+ if @possible_belongs_to_not_null_columns.present?
26
+ string += " belongs_to_presence_validations_for(#{@possible_belongs_to_not_null_columns.inspect})\n"
27
+ end
28
+ string += " belongs_to_uniqueness_validations_for(#{@unique_indexes.inspect})\n" if @unique_indexes.present?
29
+ string += " uniqueness_validations_for(#{@unique_indexes.inspect})\n" if @unique_indexes.present?
30
+ string += @validations.uniq.map { |v| " #{v}\n" }.join
31
+ "#{string}end\n"
32
+ end
33
+
34
+ def validates(attribute, validator, options = {})
35
+ @validations.push(Validation.new(attribute, validator, options))
36
+ end
37
+
38
+ def null_validation(datatype, name, column_options)
39
+ @column_names.push(name.to_s)
40
+
41
+ return if column_options[:null] != false
42
+
43
+ @possible_belongs_to_not_null_columns.push(name.to_sym) if datatype.in?(%i[bigint integer uuid])
44
+ if datatype == :boolean
45
+ validates name, :inclusion, in: [true, false], message: :blank
46
+ else
47
+ validates name, :presence
48
+ end
49
+ end
50
+
51
+ def uuid(name, column_options = {})
52
+ null_validation(:uuid, name, column_options)
53
+ end
54
+
55
+ def bigint(name, column_options = {})
56
+ null_validation(:bigint, name, column_options)
57
+
58
+ validates name, :numericality, allow_nil: true
59
+ end
60
+
61
+ def integer(name, column_options = {})
62
+ null_validation(:integer, name, column_options)
63
+
64
+ return if column_options[:array]
65
+
66
+ integer_range = ::ActiveRecord::Type::Integer.new.send(:range)
67
+ options = { allow_nil: true, only_integer: true, greater_than_or_equal_to: integer_range.begin }
68
+ if integer_range.exclude_end?
69
+ options[:less_than] = integer_range.end
70
+ else
71
+ options[:less_than_or_equal_to] = integer_range.end
72
+ end
73
+
74
+ validates name, :numericality, options
75
+ end
76
+
77
+ def datetime(name, column_options = {})
78
+ null_validation(:datetime, name, column_options)
79
+ end
80
+
81
+ def date(name, column_options = {})
82
+ null_validation(:date, name, column_options)
83
+ end
84
+
85
+ def boolean(name, column_options = {})
86
+ null_validation(:boolean, name, column_options)
87
+ end
88
+
89
+ def string(name, column_options = {})
90
+ text(name, column_options)
91
+ end
92
+
93
+ def json(name, column_options = {})
94
+ null_validation(:json, name, column_options)
95
+ end
96
+
97
+ def decimal(name, column_options = {})
98
+ null_validation(:decimal, name, column_options)
99
+ return if column_options[:array]
100
+ return if column_options[:precision].blank? || column_options[:scale].blank?
101
+
102
+ limit = 10**(column_options[:precision] - (column_options[:scale] || 0))
103
+ validates name, :numericality, allow_nil: true, greater_than: -limit, less_than: limit
104
+ end
105
+
106
+ def float(name, column_options = {})
107
+ null_validation(:float, name, column_options)
108
+ return if column_options[:array]
109
+
110
+ validates name, :numericality, allow_nil: true
111
+ end
112
+
113
+ def text(name, column_options = {})
114
+ null_validation(:text, name, column_options)
115
+ return if column_options[:array]
116
+ return if column_options[:limit].blank?
117
+
118
+ validates name, :length, allow_nil: true, maximum: column_options[:limit]
119
+ end
120
+
121
+ def index(names, index_options = {})
122
+ names = [names] unless names.is_a?(Array)
123
+ return unless index_options[:unique]
124
+ return unless names.all? { |name| name.to_s.in?(@column_names) }
125
+
126
+ @unique_indexes.push(names.map(&:to_s))
127
+ end
128
+ end
@@ -0,0 +1,8 @@
1
+ # frozen_string_literal: true
2
+
3
+ Rake::Task['db:schema:dump'].enhance do
4
+ require 'generated_schema_validations'
5
+ require_relative 'dumper'
6
+ require_relative 'table'
7
+ GeneratedSchemaValidations::Dumper.generate
8
+ end
@@ -0,0 +1,73 @@
1
+ # frozen_string_literal: true
2
+
3
+ # This file is auto-generated from the current state of the database. Instead
4
+ # of editing this file, please use the migrations feature of Active Record to
5
+ # incrementally modify your database, and then regenerate this schema definition.
6
+
7
+ # generated from version VERSION_INFO
8
+
9
+ module SchemaValidations
10
+ extend ActiveSupport::Concern
11
+
12
+ included do
13
+ class_attribute :schema_validations_excluded_columns, default: %i[id created_at updated_at type]
14
+ end
15
+
16
+ class_methods do
17
+ def schema_validations(exclude: [], schema_table_name: table_name)
18
+ self.schema_validations_excluded_columns += exclude
19
+ send("dbv_#{schema_table_name}_validations")
20
+ end
21
+
22
+ TABLE_VALIDATIONS
23
+
24
+ def validates_with_filter(attribute, options)
25
+ return if attribute.to_sym.in?(schema_validations_excluded_columns)
26
+
27
+ validates attribute, options
28
+ end
29
+
30
+ def belongs_to_presence_validations_for(not_null_columns)
31
+ reflect_on_all_associations(:belongs_to).each do |association|
32
+ if not_null_columns.include?(association.foreign_key.to_sym)
33
+ validates association.name, presence: true
34
+ schema_validations_excluded_columns.push(association.foreign_key.to_sym)
35
+ end
36
+ end
37
+ end
38
+
39
+ def belongs_to_uniqueness_validations_for(unique_indexes)
40
+ reflect_on_all_associations(:belongs_to).each do |association|
41
+ dbv_uniqueness_validations_for(unique_indexes, foreign_key: association.foreign_key.to_s,
42
+ column: association.name)
43
+ end
44
+ end
45
+
46
+ def uniqueness_validations_for(unique_indexes)
47
+ unique_indexes.each do |names|
48
+ names.each do |name|
49
+ dbv_uniqueness_validations_for(unique_indexes, foreign_key: name, column: name)
50
+ end
51
+ end
52
+ end
53
+
54
+ def dbv_uniqueness_validations_for(unique_indexes, foreign_key:, column:)
55
+ unique_indexes.each do |names|
56
+ next unless foreign_key.in?(names)
57
+
58
+ scope = (names - [foreign_key]).map(&:to_sym)
59
+ options = { allow_nil: true }
60
+ options[:scope] = scope if scope.any?
61
+ options[:if] = (proc do |record|
62
+ if scope.all? { |scope_sym| record.public_send(:"#{scope_sym}?") }
63
+ record.public_send(:"#{foreign_key}_changed?")
64
+ else
65
+ false
66
+ end
67
+ end)
68
+
69
+ validates column, uniqueness: options
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,6 @@
1
+ # frozen_string_literal: true
2
+
3
+ module GeneratedSchemaValidations
4
+ end
5
+
6
+ require_relative 'generated_schema_validations/railtie' if defined?(Rails::Railtie)
metadata ADDED
@@ -0,0 +1,60 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: generated_schema_validations
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Georg Limbach
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2022-01-07 00:00:00.000000000 Z
12
+ dependencies: []
13
+ description: After each migration it generates a file with some validations. Each
14
+ active record should include this file and can uns generated validations.
15
+ email:
16
+ - georg.limbach@lichtbit.com
17
+ executables: []
18
+ extensions: []
19
+ extra_rdoc_files: []
20
+ files:
21
+ - ".gitignore"
22
+ - ".rspec"
23
+ - Gemfile
24
+ - Gemfile.lock
25
+ - LICENSE.txt
26
+ - README.md
27
+ - Rakefile
28
+ - generated_schema_validations.gemspec
29
+ - lib/generated_schema_validations.rb
30
+ - lib/generated_schema_validations/dumper.rb
31
+ - lib/generated_schema_validations/railtie.rb
32
+ - lib/generated_schema_validations/table.rb
33
+ - lib/generated_schema_validations/tasks.rb
34
+ - lib/generated_schema_validations/template.rb
35
+ homepage: https://github.com/Lichtbit/generated_schema_validations
36
+ licenses:
37
+ - MIT
38
+ metadata:
39
+ homepage_uri: https://github.com/Lichtbit/generated_schema_validations
40
+ source_code_uri: https://github.com/Lichtbit/generated_schema_validations
41
+ post_install_message:
42
+ rdoc_options: []
43
+ require_paths:
44
+ - lib
45
+ required_ruby_version: !ruby/object:Gem::Requirement
46
+ requirements:
47
+ - - ">="
48
+ - !ruby/object:Gem::Version
49
+ version: 2.3.0
50
+ required_rubygems_version: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - ">="
53
+ - !ruby/object:Gem::Version
54
+ version: '0'
55
+ requirements: []
56
+ rubygems_version: 3.1.4
57
+ signing_key:
58
+ specification_version: 4
59
+ summary: Generate rails validations from schema.rb file
60
+ test_files: []