valhammer 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 7bbc167cf3bd0b5da8157c01558742ba809d6efb
4
+ data.tar.gz: 0e478898f5ce6d7f5338e03e0010d72179e4e06c
5
+ SHA512:
6
+ metadata.gz: d166959c57a0f15af70b4cedf85c51a8a41f676bb9fb9f8e656c1d00b7816a1685cd6b540343dce5619ed7238a5b37a7550f10a6c39014c0aee7cc6f5d59f8ec
7
+ data.tar.gz: c135af6ebcfa1d6d9a1a8dca65f11f90ac37d6bff1ca0cf9deb223523f01a218af3244eebb706e42cb6390bf22675ed6d10ede83b6c0cb1cbe4594aded4e9570
@@ -0,0 +1,17 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /spec/db/*.sqlite3
10
+ /spec/dummy/log/
11
+ /log/
12
+ /tmp/
13
+ *.bundle
14
+ *.so
15
+ *.o
16
+ *.a
17
+ mkmf.log
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --color
2
+ --require spec_helper
3
+ --format documentation
@@ -0,0 +1,2 @@
1
+ Style/Documentation:
2
+ Enabled: false
@@ -0,0 +1,10 @@
1
+ require 'coveralls'
2
+
3
+ SimpleCov.formatter = SimpleCov::Formatter::MultiFormatter[
4
+ SimpleCov::Formatter::HTMLFormatter,
5
+ Coveralls::SimpleCov::Formatter
6
+ ]
7
+
8
+ SimpleCov.start do
9
+ add_filter('spec')
10
+ end
@@ -0,0 +1,7 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.1
4
+ branches:
5
+ only:
6
+ - master
7
+ - develop
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in valhammer.gemspec
4
+ gemspec
@@ -0,0 +1,16 @@
1
+ guard :bundler do
2
+ watch('Gemfile')
3
+ watch(/^.+\.gemspec/)
4
+ end
5
+
6
+ guard :rspec, cmd: 'bundle exec rspec' do
7
+ watch(/^spec\/.+_spec\.rb$/)
8
+ watch(/^lib\/(.+)\.rb$/) { |m| "spec/lib/#{m[1]}_spec.rb" }
9
+ watch('spec/spec_helper.rb') { 'spec' }
10
+ watch(%r{spec/(db|dummy)/.*\.rb}) { 'spec' }
11
+ end
12
+
13
+ guard :rubocop do
14
+ watch(/.+\.rb$/)
15
+ watch(/(?:.+\/)?\.rubocop\.yml$/) { |m| File.dirname(m[0]) }
16
+ end
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,190 @@
1
+ # Valhammer
2
+
3
+ [![Gem Version][GV img]][Gem Version]
4
+ [![Build Status][BS img]][Build Status]
5
+ [![Dependency Status][DS img]][Dependency Status]
6
+ [![Code Climate][CC img]][Code Climate]
7
+ [![Coverage Status][CS img]][Coverage Status]
8
+
9
+ [Gem Version]: https://rubygems.org/gems/valhammer
10
+ [Build Status]: https://travis-ci.org/ausaccessfed/valhammer
11
+ [Dependency Status]: https://gemnasium.com/ausaccessfed/valhammer
12
+ [Code Climate]: https://codeclimate.com/github/ausaccessfed/valhammer
13
+ [Coverage Status]: https://coveralls.io/r/ausaccessfed/valhammer
14
+
15
+ [GV img]: https://img.shields.io/gem/v/valhammer.svg
16
+ [BS img]: https://img.shields.io/travis/ausaccessfed/valhammer/develop.svg
17
+ [DS img]: https://img.shields.io/gemnasium/ausaccessfed/valhammer.svg
18
+ [CC img]: https://img.shields.io/codeclimate/github/ausaccessfed/valhammer.svg
19
+ [CS img]: https://img.shields.io/coveralls/ausaccessfed/valhammer.svg
20
+
21
+ Automatically validate ActiveRecord models based on the database schema.
22
+
23
+ Author: Shaun Mangelsdorf
24
+
25
+ ```
26
+ Copyright 2015, Australian Access Federation
27
+
28
+ Licensed under the Apache License, Version 2.0 (the "License");
29
+ you may not use this file except in compliance with the License.
30
+ You may obtain a copy of the License at
31
+
32
+ http://www.apache.org/licenses/LICENSE-2.0
33
+
34
+ Unless required by applicable law or agreed to in writing, software
35
+ distributed under the License is distributed on an "AS IS" BASIS,
36
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
37
+ See the License for the specific language governing permissions and
38
+ limitations under the License.
39
+ ```
40
+
41
+ ## Installation
42
+
43
+ Add this line to your application's Gemfile:
44
+
45
+ ```ruby
46
+ gem 'valhammer'
47
+ ```
48
+
49
+ Use Bundler to install the dependency:
50
+
51
+ ```
52
+ bundle install
53
+ ```
54
+
55
+ In Rails, Valhammer is automatically added to `ActiveRecord::Base`. If you're
56
+ using ActiveRecord outside of Rails, you may have to do this yourself:
57
+
58
+ ```ruby
59
+ ActiveRecord::Base.extend(Valhammer::Validations)
60
+ ```
61
+
62
+ ## Usage
63
+
64
+ Call the `valhammer` method inside your model class, after any `belongs_to`
65
+ relationships are defined:
66
+
67
+ ```ruby
68
+ class Widget < ActiveRecord::Base
69
+ belongs_to :supplier
70
+
71
+ valhammer
72
+ end
73
+ ```
74
+
75
+ Generated validations are:
76
+
77
+ * `:presence` &mdash; added to non-nullable, non-boolean columns
78
+ * `:inclusion` &mdash; added to boolean columns to emulate the functionality of
79
+ `presence` which doesn't work correctly for booleans
80
+ * `:uniqueness` &mdash; added to match unique keys
81
+ * `:numericality` &mdash; added to `integer`/`decimal` columns with the
82
+ `only_integer` option set appropriately
83
+ * `:length` &mdash; added to `string` columns to ensure the value fits in the
84
+ column
85
+
86
+ To disable a kind of validation, pass an option to the `valhammer` method:
87
+
88
+ ```ruby
89
+ class Widget < ActiveRecord::Base
90
+ belongs_to :supplier
91
+
92
+ valhammer uniqueness: false
93
+ end
94
+ ```
95
+
96
+ ## Composite Unique Keys
97
+
98
+ When Valhammer encounters a composite unique key, it inspects the columns
99
+ involved in the key and uses them to build a `scope`. For example:
100
+
101
+ ```ruby
102
+ create_table(:widgets) do |t|
103
+ t.string :supplier_code, null: false, default: nil
104
+ t.string :item_code, null: false, default: nil
105
+
106
+ t.index [:supplier_code, :item_code], unique: true
107
+ end
108
+ ```
109
+
110
+ When this table is examined by Valhammer, the uniqueness validation created will
111
+ be the same as if you had written:
112
+
113
+ ```ruby
114
+ class Widget < ActiveRecord::Base
115
+ validates :item_code, uniqueness: { scope: :supplier_code }
116
+ end
117
+ ```
118
+
119
+ That is, the last column in the key is the field which gets validated, and the
120
+ other columns form the `scope` argument.
121
+
122
+ ## Duplicate Unique Keys
123
+
124
+ Valhammer is able to handle the simple case when multiple unique keys reference
125
+ the same field, as in the following contrived example:
126
+
127
+ ```ruby
128
+ create_table(:order_update) do |t|
129
+ t.belongs_to :order
130
+ t.string :state
131
+ t.string :identifier
132
+
133
+ t.index [:order_id, :state], unique: true
134
+ t.index [:order_id, :state, :identifier], unique: true
135
+ end
136
+ ```
137
+
138
+ Uniqueness validations are created as though the model was defined using:
139
+
140
+ ```ruby
141
+ class OrderUpdate < ActiveRecord::Base
142
+ validates :state, uniqueness: { scope: :order_id }
143
+ validates :identifier, uniqueness: { scope: [:order_id, :state] }
144
+ end
145
+ ```
146
+
147
+ In the case where multiple unique keys have the same column in the last
148
+ position, Valhammer is unable to determine which is the "authoritative" scope
149
+ for the validation. Take the following contrived example:
150
+
151
+ ```ruby
152
+ create_table(:order_enquiry) do |t|
153
+ t.belongs_to :order
154
+ t.belongs_to :customer
155
+ t.string :date
156
+
157
+ t.index [:order_id, :date], unique: true
158
+ t.index [:customer_id, :date], unique: true
159
+ end
160
+ ```
161
+
162
+ Valhammer is unable to resolve which `scope` to apply, so no `uniqueness`
163
+ validation is applied.
164
+
165
+ ## Unique Keys and Associations
166
+
167
+ In the case where a foreign key is the last column in a key, that key will not
168
+ be given a uniqueness validation.
169
+
170
+ ```ruby
171
+ create_table(:order_payment) do |t|
172
+ t.belongs_to :customer
173
+ t.string :reference
174
+ t.boolean :complete
175
+ t.integer :amount
176
+
177
+ t.index [:reference, :customer_id], unique: true
178
+ end
179
+ ```
180
+
181
+ To work around this, put associations first in your unique keys (often a
182
+ [good idea](http://dev.mysql.com/doc/refman/5.6/en/multiple-column-indexes.html)
183
+ anyway, if it means your association queries benefit from the index).
184
+
185
+ Alternatively, apply the validation yourself using ActiveRecord.
186
+
187
+ ## Contributing
188
+
189
+ Refer to [GitHub Flow](https://guides.github.com/introduction/flow/) for
190
+ help contributing to this project.
@@ -0,0 +1,8 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rspec/core/rake_task'
3
+ require 'rubocop/rake_task'
4
+
5
+ RSpec::Core::RakeTask.new(:spec)
6
+ RuboCop::RakeTask.new
7
+
8
+ task default: [:spec, :rubocop]
@@ -0,0 +1,7 @@
1
+ require 'valhammer/version'
2
+
3
+ module Valhammer
4
+ end
5
+
6
+ require 'valhammer/validations'
7
+ require 'valhammer/railtie' if defined?(Rails::Railtie)
@@ -0,0 +1,9 @@
1
+ module Valhammer
2
+ class Railtie < ::Rails::Railtie
3
+ initializer 'valhammer.install' do
4
+ ActiveSupport.on_load(:active_record) do
5
+ ActiveRecord::Base.extend Valhammer::Validations
6
+ end
7
+ end
8
+ end
9
+ end
@@ -0,0 +1,112 @@
1
+ module Valhammer
2
+ module Validations
3
+ VALHAMMER_DEFAULT_OPTS = { presence: true, uniqueness: true,
4
+ numericality: true, length: true,
5
+ inclusion: true }.freeze
6
+
7
+ VALHAMMER_EXCLUDED_FIELDS = %w(created_at updated_at)
8
+
9
+ private_constant :VALHAMMER_DEFAULT_OPTS, :VALHAMMER_EXCLUDED_FIELDS
10
+
11
+ def valhammer(opts = {})
12
+ @valhammer_indexes ||= connection.indexes(table_name)
13
+ opts = VALHAMMER_DEFAULT_OPTS.merge(opts)
14
+ columns_hash.each do |name, column|
15
+ valhammer_validate(name, column, opts)
16
+ end
17
+ end
18
+
19
+ private
20
+
21
+ def valhammer_validate(name, column, opts)
22
+ return if valhammer_exclude?(name)
23
+
24
+ assoc_name = valhammer_assoc_name(name)
25
+ if assoc_name.nil?
26
+ validations = valhammer_validations(column, opts)
27
+ validates(name, validations) unless validations.empty?
28
+ return
29
+ end
30
+
31
+ return if column.null || !opts[:presence]
32
+ validates(assoc_name, presence: true)
33
+ end
34
+
35
+ def valhammer_validations(column, opts)
36
+ logger.debug("Valhammer generating options for #{valhammer_info(column)}")
37
+
38
+ validations = {}
39
+ valhammer_presence(validations, column, opts)
40
+ valhammer_inclusion(validations, column, opts)
41
+ valhammer_unique(validations, column, opts)
42
+ valhammer_numeric(validations, column, opts)
43
+ valhammer_length(validations, column, opts)
44
+
45
+ logger.debug("Valhammer options for #{valhammer_log_key(column)} " \
46
+ "are: #{validations.inspect}")
47
+ validations
48
+ end
49
+
50
+ def valhammer_presence(validations, column, opts)
51
+ return unless opts[:presence] && column.type != :boolean
52
+
53
+ validations[:presence] = true unless column.null
54
+ end
55
+
56
+ def valhammer_inclusion(validations, column, opts)
57
+ return unless opts[:inclusion] && column.type == :boolean
58
+
59
+ validations[:inclusion] = { in: [false, true], allow_nil: column.null }
60
+ end
61
+
62
+ def valhammer_unique(validations, column, opts)
63
+ return unless opts[:uniqueness]
64
+
65
+ unique_keys = @valhammer_indexes.select do |i|
66
+ i.unique && i.columns.last == column.name
67
+ end
68
+
69
+ return unless unique_keys.one?
70
+
71
+ scope = unique_keys.first.columns[0..-2]
72
+ validations[:uniqueness] = scope.empty? ? true : { scope: scope }
73
+ end
74
+
75
+ def valhammer_numeric(validations, column, opts)
76
+ return unless opts[:numericality]
77
+
78
+ case column.type
79
+ when :integer
80
+ validations[:numericality] = { only_integer: true,
81
+ allow_nil: column.null }
82
+ when :decimal
83
+ validations[:numericality] = { only_integer: false,
84
+ allow_nil: column.null }
85
+ end
86
+ end
87
+
88
+ def valhammer_length(validations, column, opts)
89
+ return unless opts[:length] && column.type == :string && column.limit
90
+
91
+ validations[:length] = { maximum: column.limit }
92
+ end
93
+
94
+ def valhammer_log_key(column)
95
+ "`#{table_name}`.`#{column.name}`"
96
+ end
97
+
98
+ def valhammer_info(column)
99
+ "#{valhammer_log_key(column)} (type=:#{column.type} " \
100
+ "null=#{column.null || 'false'} limit=#{column.limit || 'nil'})"
101
+ end
102
+
103
+ def valhammer_exclude?(field)
104
+ field == primary_key || VALHAMMER_EXCLUDED_FIELDS.include?(field)
105
+ end
106
+
107
+ def valhammer_assoc_name(field)
108
+ reflect_on_all_associations(:belongs_to)
109
+ .find { |a| a.foreign_key == field }.try(:name)
110
+ end
111
+ end
112
+ end
@@ -0,0 +1,3 @@
1
+ module Valhammer
2
+ VERSION = '0.1.0'
3
+ end
@@ -0,0 +1,40 @@
1
+ ActiveRecord::Schema.define(version: 0) do
2
+ create_table :resources, force: true do |t|
3
+ t.belongs_to :organisation, null: false, default: nil
4
+
5
+ t.string :name, null: false, default: nil, limit: 100
6
+ t.string :mail, null: false, default: nil
7
+ t.string :identifier, null: false, default: nil
8
+ t.string :description, null: true, default: nil
9
+ t.integer :age, null: true, default: nil
10
+ t.decimal :gpa, null: false, default: 3.0
11
+ t.integer :socialness, null: false, default: 5
12
+ t.boolean :injected, null: false, default: false
13
+
14
+ t.timestamps null: false
15
+
16
+ t.index :identifier, unique: true
17
+ end
18
+
19
+ create_table :capabilities, force: true do |t|
20
+ t.belongs_to :organisation, null: true, default: nil
21
+
22
+ t.string :name, null: false, default: nil
23
+ t.boolean :core, null: true, default: nil
24
+
25
+ t.timestamps null: false
26
+
27
+ t.index [:organisation_id, :name], unique: true
28
+ end
29
+
30
+ create_table :organisations, force: true do |t|
31
+ t.string :name, null: false
32
+ t.string :country, null: false
33
+ t.string :city, null: false
34
+
35
+ t.timestamps null: false
36
+
37
+ t.index [:country, :name], unique: true
38
+ t.index [:city, :name], unique: true
39
+ end
40
+ end
@@ -0,0 +1,5 @@
1
+ class Capability < ActiveRecord::Base
2
+ belongs_to :organisation
3
+
4
+ valhammer
5
+ end
@@ -0,0 +1,6 @@
1
+ class Organisation < ActiveRecord::Base
2
+ has_many :resources
3
+ has_many :capabilities
4
+
5
+ valhammer
6
+ end
@@ -0,0 +1,5 @@
1
+ class Resource < ActiveRecord::Base
2
+ belongs_to :organisation
3
+
4
+ valhammer
5
+ end
@@ -0,0 +1,2 @@
1
+ require ::File.expand_path('../config/environment', __FILE__)
2
+ run Rails.application
@@ -0,0 +1,14 @@
1
+ require File.expand_path('../boot', __FILE__)
2
+
3
+ require 'active_record/railtie'
4
+ require 'valhammer'
5
+
6
+ module Dummy
7
+ class Application < Rails::Application
8
+ config.cache_classes = true
9
+ config.eager_load = false
10
+
11
+ config.consider_all_requests_local = true
12
+ config.action_dispatch.show_exceptions = false
13
+ end
14
+ end
@@ -0,0 +1,4 @@
1
+ ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../../Gemfile', __FILE__)
2
+
3
+ require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE'])
4
+ $LOAD_PATH.unshift File.expand_path('../../../../lib', __FILE__)
@@ -0,0 +1,5 @@
1
+ test:
2
+ adapter: sqlite3
3
+ pool: 1
4
+ timeout: 5000
5
+ database: '../db/test.sqlite3'
@@ -0,0 +1,2 @@
1
+ require File.expand_path('../application', __FILE__)
2
+ Rails.application.initialize!
@@ -0,0 +1,2 @@
1
+ test:
2
+ secret_key_base: 890f88caa9641d1845e85a49fd9aedbd30cf507f223dcb1cb6ccc53ba23731d
@@ -0,0 +1,233 @@
1
+ RSpec.describe Valhammer::Validations do
2
+ def validation_impl(kind)
3
+ name = "#{kind.to_s.camelize}Validator"
4
+
5
+ if ActiveRecord::Validations.const_defined?(name)
6
+ ActiveRecord::Validations.const_get(name)
7
+ else
8
+ ActiveModel::Validations.const_get(name)
9
+ end
10
+ end
11
+
12
+ RSpec::Matchers.define :a_validator_for do |field, kind, opts = nil|
13
+ match do |v|
14
+ v.is_a?(validation_impl(kind)) && (opts.nil? || v.options == opts) &&
15
+ v.attributes.map(&:to_s) == [field.to_s]
16
+ end
17
+
18
+ description do
19
+ "a #{kind.inspect} validator for #{field.inspect}" \
20
+ "#{opts && " with options: #{opts.inspect}"}"
21
+ end
22
+ end
23
+
24
+ RSpec::Matchers.define_negated_matcher :not_include, :include
25
+
26
+ subject { Resource.validators }
27
+
28
+ context 'with non-nullable columns' do
29
+ it { is_expected.not_to include(a_validator_for(:id, :presence)) }
30
+ it { is_expected.not_to include(a_validator_for(:created_at, :presence)) }
31
+ it { is_expected.not_to include(a_validator_for(:updated_at, :presence)) }
32
+ it { is_expected.to include(a_validator_for(:name, :presence)) }
33
+ it { is_expected.to include(a_validator_for(:mail, :presence)) }
34
+ it { is_expected.to include(a_validator_for(:identifier, :presence)) }
35
+ it { is_expected.not_to include(a_validator_for(:description, :presence)) }
36
+ it { is_expected.to include(a_validator_for(:gpa, :presence)) }
37
+ it { is_expected.not_to include(a_validator_for(:injected, :presence)) }
38
+ end
39
+
40
+ context 'with a non-nullable boolean' do
41
+ let(:opts) { { in: [false, true], allow_nil: false } }
42
+
43
+ it { is_expected.to include(a_validator_for(:injected, :inclusion, opts)) }
44
+ end
45
+
46
+ context 'with a nullable boolean' do
47
+ subject { Capability.validators }
48
+ let(:opts) { { in: [false, true], allow_nil: true } }
49
+
50
+ it { is_expected.to include(a_validator_for(:core, :inclusion, opts)) }
51
+ end
52
+
53
+ context 'with a non-nullable association' do
54
+ it { is_expected.to include(a_validator_for(:organisation, :presence)) }
55
+
56
+ it 'excludes numericality validator' do
57
+ expect(subject)
58
+ .not_to include(a_validator_for(:organisation, :numericality))
59
+ end
60
+
61
+ it 'excludes validators on the foreign key' do
62
+ expect(subject)
63
+ .not_to include(a_validator_for(:organisation_id, :presence))
64
+ expect(subject)
65
+ .not_to include(a_validator_for(:organisation_id, :numericality))
66
+ end
67
+ end
68
+
69
+ context 'with a nullable association' do
70
+ subject { Capability.validators }
71
+
72
+ it { is_expected.not_to include(a_validator_for(:organisation, :presence)) }
73
+
74
+ it 'excludes validators on the foreign key' do
75
+ expect(subject)
76
+ .not_to include(a_validator_for(:organisation_id, :presence))
77
+ expect(subject)
78
+ .not_to include(a_validator_for(:organisation_id, :numericality))
79
+ end
80
+ end
81
+
82
+ context 'with a unique index' do
83
+ it { is_expected.not_to include(a_validator_for(:id, :uniqueness)) }
84
+ it { is_expected.to include(a_validator_for(:identifier, :uniqueness)) }
85
+ it { is_expected.not_to include(a_validator_for(:mail, :uniqueness)) }
86
+ end
87
+
88
+ context 'with a composite unique index' do
89
+ subject { Capability.validators }
90
+
91
+ let(:opts) { { scope: ['organisation_id'], case_sensitive: true } }
92
+ it { is_expected.to include(a_validator_for(:name, :uniqueness, opts)) }
93
+ end
94
+
95
+ context 'with duplicate unique indexes' do
96
+ subject { Organisation.validators }
97
+
98
+ it { is_expected.not_to include(a_validator_for(:name, :uniqueness)) }
99
+ it { is_expected.not_to include(a_validator_for(:country, :uniqueness)) }
100
+ it { is_expected.not_to include(a_validator_for(:city, :uniqueness)) }
101
+ end
102
+
103
+ context 'with an integer column' do
104
+ context 'with allow_nil' do
105
+ let(:opts) { { only_integer: true, allow_nil: true } }
106
+ it { is_expected.to include(a_validator_for(:age, :numericality, opts)) }
107
+ end
108
+ context 'without allow_nil' do
109
+ let(:opts) { { only_integer: true, allow_nil: false } }
110
+ it 'sets allow_nil to false for socialness' do
111
+ expect(subject)
112
+ .to include(a_validator_for(:socialness, :numericality, opts))
113
+ end
114
+ end
115
+ end
116
+
117
+ context 'with a numeric column' do
118
+ let(:opts) { { only_integer: false, allow_nil: false } }
119
+ it { is_expected.to include(a_validator_for(:gpa, :numericality, opts)) }
120
+ end
121
+
122
+ context 'with a limited length string' do
123
+ it { is_expected.to include(a_validator_for(:name, :length, maximum: 100)) }
124
+ end
125
+
126
+ context 'with disabled validations' do
127
+ around do |example|
128
+ old = ActiveRecord::Base.logger
129
+
130
+ begin
131
+ ActiveRecord::Base.logger = Logger.new('/dev/null')
132
+ example.run
133
+ ensure
134
+ ActiveRecord::Base.logger = old
135
+ end
136
+ end
137
+
138
+ let(:klass) do
139
+ opts = { disabled_validator => false }
140
+ Class.new(ActiveRecord::Base) do
141
+ self.table_name = 'resources'
142
+
143
+ belongs_to :organisation
144
+
145
+ valhammer(opts)
146
+ end
147
+ end
148
+
149
+ subject { klass.validators }
150
+
151
+ context ':presence' do
152
+ let(:disabled_validator) { :presence }
153
+
154
+ it 'excludes the presence validator' do
155
+ expect(subject)
156
+ .to not_include(a_validator_for(:name, :presence))
157
+ .and not_include(a_validator_for(:mail, :presence))
158
+ .and not_include(a_validator_for(:identifier, :presence))
159
+ .and not_include(a_validator_for(:gpa, :presence))
160
+ .and not_include(a_validator_for(:organisation, :presence))
161
+ end
162
+ end
163
+
164
+ context ':inclusion' do
165
+ let(:disabled_validator) { :inclusion }
166
+
167
+ it 'excludes the inclusion validator' do
168
+ expect(subject)
169
+ .not_to include(a_validator_for(:injected, :inclusion))
170
+ end
171
+ end
172
+
173
+ context ':uniqueness' do
174
+ let(:disabled_validator) { :uniqueness }
175
+
176
+ it 'excludes the uniqueness validator' do
177
+ expect(subject)
178
+ .not_to include(a_validator_for(:identifier, :uniqueness))
179
+ end
180
+ end
181
+
182
+ context ':numericality' do
183
+ let(:disabled_validator) { :numericality }
184
+
185
+ it 'excludes the numericality validator' do
186
+ expect(subject).to not_include(a_validator_for(:age, :numericality))
187
+ .and not_include(a_validator_for(:gpa, :numericality))
188
+ end
189
+ end
190
+
191
+ context ':length' do
192
+ let(:disabled_validator) { :length }
193
+
194
+ it 'excludes the length validator' do
195
+ expect(subject).not_to include(a_validator_for(:name, :length))
196
+ end
197
+ end
198
+ end
199
+
200
+ context 'sanity check' do
201
+ around do |example|
202
+ ActiveRecord::Base.transaction do
203
+ example.run
204
+ fail(ActiveRecord::Rollback)
205
+ end
206
+ end
207
+
208
+ let(:organisation) do
209
+ Organisation.create!(name: 'Enhanced Collaborative Methodologies Pty Ltd',
210
+ country: 'Australia', city: 'Brisbane')
211
+ end
212
+
213
+ context Resource do
214
+ subject do
215
+ Resource.new(name: 'Orson Orchestrator', identifier: 'orson',
216
+ mail: 'orson@synergize.example.com',
217
+ description: 'A dedicated but indifferent resource',
218
+ gpa: 3.5, injected: false, organisation: organisation)
219
+ end
220
+
221
+ it { is_expected.to be_valid }
222
+ end
223
+
224
+ context Capability do
225
+ subject do
226
+ Capability.create!(organisation: organisation, core: true,
227
+ name: 'Project Management')
228
+ end
229
+
230
+ it { is_expected.to be_valid }
231
+ end
232
+ end
233
+ end
@@ -0,0 +1,26 @@
1
+ Bundler.setup
2
+ require 'simplecov'
3
+
4
+ ENV['RAILS_ENV'] = 'test'
5
+ FileUtils.rm_f 'spec/db/test.sqlite3'
6
+
7
+ require_relative 'dummy/config/environment.rb'
8
+ require_relative 'db/schema.rb'
9
+
10
+ RSpec.configure do |config|
11
+ config.expect_with :rspec do |expectations|
12
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
13
+ end
14
+
15
+ config.mock_with :rspec do |mocks|
16
+ mocks.verify_partial_doubles = true
17
+ end
18
+
19
+ config.filter_run :focus
20
+ config.run_all_when_everything_filtered = true
21
+
22
+ config.disable_monkey_patching!
23
+
24
+ config.order = :random
25
+ Kernel.srand config.seed
26
+ end
@@ -0,0 +1,33 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'valhammer/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'valhammer'
8
+ spec.version = Valhammer::VERSION
9
+ spec.authors = ['Shaun Mangelsdorf']
10
+ spec.email = ['s.mangelsdorf@gmail.com']
11
+ spec.summary = 'Automatically validate ActiveRecord models based on ' \
12
+ 'the database schema.'
13
+ spec.homepage = 'https://github.com/ausaccessfed/valhammer'
14
+ spec.license = 'Apache-2.0'
15
+
16
+ spec.files = `git ls-files -z`.split("\x0")
17
+ spec.executables = spec.files.grep(/^bin\//) { |f| File.basename(f) }
18
+ spec.test_files = spec.files.grep(/^(test|spec|features)\//)
19
+ spec.require_paths = ['lib']
20
+
21
+ spec.add_dependency 'activerecord', '~> 4.1'
22
+
23
+ spec.add_development_dependency 'rails', '~> 4.1'
24
+ spec.add_development_dependency 'bundler', '~> 1.7'
25
+ spec.add_development_dependency 'rake', '~> 10.0'
26
+ spec.add_development_dependency 'guard'
27
+ spec.add_development_dependency 'guard-rubocop'
28
+ spec.add_development_dependency 'guard-rspec'
29
+ spec.add_development_dependency 'guard-bundler'
30
+ spec.add_development_dependency 'simplecov'
31
+ spec.add_development_dependency 'coveralls'
32
+ spec.add_development_dependency 'sqlite3'
33
+ end
metadata ADDED
@@ -0,0 +1,237 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: valhammer
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Shaun Mangelsdorf
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-03-02 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: activerecord
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '4.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '4.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rails
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '4.1'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '4.1'
41
+ - !ruby/object:Gem::Dependency
42
+ name: bundler
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '1.7'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '1.7'
55
+ - !ruby/object:Gem::Dependency
56
+ name: rake
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - "~>"
60
+ - !ruby/object:Gem::Version
61
+ version: '10.0'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - "~>"
67
+ - !ruby/object:Gem::Version
68
+ version: '10.0'
69
+ - !ruby/object:Gem::Dependency
70
+ name: guard
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ">="
74
+ - !ruby/object:Gem::Version
75
+ version: '0'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ">="
81
+ - !ruby/object:Gem::Version
82
+ version: '0'
83
+ - !ruby/object:Gem::Dependency
84
+ name: guard-rubocop
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: guard-rspec
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: guard-bundler
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ">="
116
+ - !ruby/object:Gem::Version
117
+ version: '0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ">="
123
+ - !ruby/object:Gem::Version
124
+ version: '0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: simplecov
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ">="
130
+ - !ruby/object:Gem::Version
131
+ version: '0'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ">="
137
+ - !ruby/object:Gem::Version
138
+ version: '0'
139
+ - !ruby/object:Gem::Dependency
140
+ name: coveralls
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ">="
144
+ - !ruby/object:Gem::Version
145
+ version: '0'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ">="
151
+ - !ruby/object:Gem::Version
152
+ version: '0'
153
+ - !ruby/object:Gem::Dependency
154
+ name: sqlite3
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ">="
158
+ - !ruby/object:Gem::Version
159
+ version: '0'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ">="
165
+ - !ruby/object:Gem::Version
166
+ version: '0'
167
+ description:
168
+ email:
169
+ - s.mangelsdorf@gmail.com
170
+ executables: []
171
+ extensions: []
172
+ extra_rdoc_files: []
173
+ files:
174
+ - ".gitignore"
175
+ - ".rspec"
176
+ - ".rubocop.yml"
177
+ - ".simplecov"
178
+ - ".travis.yml"
179
+ - Gemfile
180
+ - Guardfile
181
+ - LICENSE
182
+ - README.md
183
+ - Rakefile
184
+ - lib/valhammer.rb
185
+ - lib/valhammer/railtie.rb
186
+ - lib/valhammer/validations.rb
187
+ - lib/valhammer/version.rb
188
+ - spec/db/schema.rb
189
+ - spec/dummy/app/models/capability.rb
190
+ - spec/dummy/app/models/organisation.rb
191
+ - spec/dummy/app/models/resource.rb
192
+ - spec/dummy/config.ru
193
+ - spec/dummy/config/application.rb
194
+ - spec/dummy/config/boot.rb
195
+ - spec/dummy/config/database.yml
196
+ - spec/dummy/config/environment.rb
197
+ - spec/dummy/config/secrets.yml
198
+ - spec/lib/valhammer/validations_spec.rb
199
+ - spec/spec_helper.rb
200
+ - valhammer.gemspec
201
+ homepage: https://github.com/ausaccessfed/valhammer
202
+ licenses:
203
+ - Apache-2.0
204
+ metadata: {}
205
+ post_install_message:
206
+ rdoc_options: []
207
+ require_paths:
208
+ - lib
209
+ required_ruby_version: !ruby/object:Gem::Requirement
210
+ requirements:
211
+ - - ">="
212
+ - !ruby/object:Gem::Version
213
+ version: '0'
214
+ required_rubygems_version: !ruby/object:Gem::Requirement
215
+ requirements:
216
+ - - ">="
217
+ - !ruby/object:Gem::Version
218
+ version: '0'
219
+ requirements: []
220
+ rubyforge_project:
221
+ rubygems_version: 2.2.2
222
+ signing_key:
223
+ specification_version: 4
224
+ summary: Automatically validate ActiveRecord models based on the database schema.
225
+ test_files:
226
+ - spec/db/schema.rb
227
+ - spec/dummy/app/models/capability.rb
228
+ - spec/dummy/app/models/organisation.rb
229
+ - spec/dummy/app/models/resource.rb
230
+ - spec/dummy/config.ru
231
+ - spec/dummy/config/application.rb
232
+ - spec/dummy/config/boot.rb
233
+ - spec/dummy/config/database.yml
234
+ - spec/dummy/config/environment.rb
235
+ - spec/dummy/config/secrets.yml
236
+ - spec/lib/valhammer/validations_spec.rb
237
+ - spec/spec_helper.rb