unique_attributes 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.
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 70a00c890458b0211c83d2c03761dc25076d3eca
4
+ data.tar.gz: fe8105fe343e4eb9b88fe05b49e9d64cdf77526a
5
+ SHA512:
6
+ metadata.gz: f7ac7936da0e54159abd1ef4e92240b2cdbf449cbe960eb45b830e037e1798c64a14f287020958f78721991e68321bbe02198abb4fa8f054e3d1dae2ae91238a
7
+ data.tar.gz: 576ebc540a990b71865ecbbd9bc919802308efe216ae7f910c171b0f4c5f1b19fbebaf32042e10b87c1e028dfd214ae8f31311bc9d351506bbe66485eba302af
@@ -0,0 +1,15 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
10
+ *.bundle
11
+ *.so
12
+ *.o
13
+ *.a
14
+ mkmf.log
15
+ *.gem
@@ -0,0 +1,7 @@
1
+ PreCommit:
2
+ Brakeman:
3
+ enabled: false # Disable Brakeman since this isn't a Rails app.
4
+ RailsSchemaUpToDate:
5
+ enabled: false
6
+ Reek:
7
+ enabled: false
@@ -0,0 +1,265 @@
1
+ # This (http://c2.com/cgi/wiki?AbcMetric) is super obnoxious
2
+ AbcSize:
3
+ Enabled: false
4
+
5
+ AccessorMethodName:
6
+ Enabled: false
7
+
8
+ Alias:
9
+ Enabled: false
10
+
11
+ AllCops:
12
+ Exclude:
13
+ - "vendor/**/*"
14
+ - "spec/dummy/**/*"
15
+ - "db/schema.rb"
16
+ - "db/migrate/**/*"
17
+ RunRailsCops: true
18
+
19
+ AmbiguousOperator:
20
+ Enabled: false
21
+
22
+ AmbiguousRegexpLiteral:
23
+ Enabled: false
24
+
25
+ ArrayJoin:
26
+ Enabled: false
27
+
28
+ AsciiComments:
29
+ Enabled: false
30
+
31
+ AsciiIdentifiers:
32
+ Enabled: false
33
+
34
+ AssignmentInCondition:
35
+ Enabled: true
36
+
37
+ Attr:
38
+ Enabled: false
39
+
40
+ BlockNesting:
41
+ Enabled: false
42
+
43
+ BracesAroundHashParameters:
44
+ Enabled: false
45
+
46
+ CaseEquality:
47
+ Enabled: false
48
+
49
+ CharacterLiteral:
50
+ Enabled: false
51
+
52
+ ClassLength:
53
+ Enabled: false
54
+
55
+ ClassVars:
56
+ Enabled: false
57
+
58
+ CollectionMethods:
59
+ PreferredMethods:
60
+ find: detect
61
+ reduce: inject
62
+ collect: map
63
+ find_all: select
64
+
65
+ ColonMethodCall:
66
+ Enabled: false
67
+
68
+ CommentAnnotation:
69
+ Enabled: false
70
+
71
+ ConditionPosition:
72
+ Enabled: false
73
+
74
+ CyclomaticComplexity:
75
+ Enabled: false
76
+
77
+ Delegate:
78
+ Enabled: false
79
+
80
+ DeprecatedClassMethods:
81
+ Enabled: false
82
+
83
+ DeprecatedHashMethods:
84
+ Enabled: false
85
+
86
+ Documentation:
87
+ Enabled: false
88
+
89
+ DotPosition:
90
+ EnforcedStyle: trailing
91
+
92
+ DoubleNegation:
93
+ Enabled: false
94
+
95
+ ElseLayout:
96
+ Enabled: false
97
+
98
+ EmptyLiteral:
99
+ Enabled: false
100
+
101
+ Encoding:
102
+ Enabled: false
103
+
104
+ EvenOdd:
105
+ Enabled: false
106
+
107
+ FileName:
108
+ Enabled: false
109
+
110
+ FlipFlop:
111
+ Enabled: false
112
+
113
+ FormatString:
114
+ Enabled: false
115
+
116
+ GlobalVars:
117
+ Enabled: false
118
+
119
+ GuardClause:
120
+ Enabled: false
121
+
122
+ HandleExceptions:
123
+ Enabled: false
124
+
125
+ IfUnlessModifier:
126
+ Enabled: false
127
+
128
+ IfWithSemicolon:
129
+ Enabled: false
130
+
131
+ InvalidCharacterLiteral:
132
+ Enabled: false
133
+
134
+ Lambda:
135
+ Enabled: false
136
+
137
+ LambdaCall:
138
+ Enabled: false
139
+
140
+ LineEndConcatenation:
141
+ Enabled: false
142
+
143
+ LineLength:
144
+ Max: 80
145
+
146
+ LiteralInCondition:
147
+ Enabled: false
148
+
149
+ LiteralInInterpolation:
150
+ Enabled: false
151
+
152
+ Loop:
153
+ Enabled: false
154
+
155
+ MethodLength:
156
+ Enabled: false
157
+
158
+ ModuleFunction:
159
+ Enabled: false
160
+
161
+ NegatedIf:
162
+ Enabled: false
163
+
164
+ NegatedWhile:
165
+ Enabled: false
166
+
167
+ Next:
168
+ Enabled: false
169
+
170
+ NilComparison:
171
+ Enabled: false
172
+
173
+ Not:
174
+ Enabled: false
175
+
176
+ NumericLiterals:
177
+ Enabled: false
178
+
179
+ OneLineConditional:
180
+ Enabled: false
181
+
182
+ OpMethod:
183
+ Enabled: false
184
+
185
+ ParameterLists:
186
+ Enabled: false
187
+
188
+ ParenthesesAsGroupedExpression:
189
+ Enabled: false
190
+
191
+ PercentLiteralDelimiters:
192
+ PreferredDelimiters:
193
+ '%': '{}'
194
+
195
+ PerceivedComplexity:
196
+ Enabled: false
197
+
198
+ PerlBackrefs:
199
+ Enabled: false
200
+
201
+ PredicateName:
202
+ Enabled: false
203
+
204
+ Proc:
205
+ Enabled: false
206
+
207
+ RaiseArgs:
208
+ Enabled: false
209
+
210
+ RedundantReturn:
211
+ AllowMultipleReturnValues: true
212
+
213
+ RegexpLiteral:
214
+ Enabled: false
215
+
216
+ RequireParentheses:
217
+ Enabled: false
218
+
219
+ SelfAssignment:
220
+ Enabled: false
221
+
222
+ SignalException:
223
+ EnforcedStyle: only_raise
224
+
225
+ SingleLineBlockParams:
226
+ Enabled: false
227
+
228
+ SingleLineMethods:
229
+ Enabled: false
230
+
231
+ SpecialGlobalVars:
232
+ Enabled: false
233
+
234
+ StringLiterals:
235
+ EnforcedStyle: double_quotes
236
+
237
+ Style/MultilineBlockChain:
238
+ Enabled: false
239
+
240
+ VariableInterpolation:
241
+ Enabled: false
242
+
243
+ TrailingComma:
244
+ Enabled: false
245
+
246
+ TrivialAccessors:
247
+ Enabled: false
248
+
249
+ UnderscorePrefixedVariableName:
250
+ Enabled: false
251
+
252
+ VariableInterpolation:
253
+ Enabled: false
254
+
255
+ Void:
256
+ Enabled: false
257
+
258
+ WhenThen:
259
+ Enabled: false
260
+
261
+ WhileUntilModifier:
262
+ Enabled: false
263
+
264
+ WordArray:
265
+ Enabled: false
@@ -0,0 +1,16 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.0.0
4
+ - 2.1.4
5
+ before_script:
6
+ - psql -c 'create database unique_attributes_test;' -U postgres
7
+ script: bundle exec rspec
8
+ addons:
9
+ postgresql: "9.3"
10
+ code_climate:
11
+ repo_token: 77d19511a3073b3dcadd6b4abbc87e5dd46c3db1ba6815a32545e91d9996d820
12
+ notifications:
13
+ email: false
14
+ hipchat:
15
+ rooms:
16
+ secure: Q3zxZGqtrcbhw3S038A1LSmWks5uEKxKUjGee5q30PWCkoNEg9VxgbcMH2ZzMA10BCvHcKMI4yUk7yy/WyO8UKYprFA8707M7FjBmxfY62GK9K58sPBDUrnpCAfxGqyZZ1oXofSJamNPHh3G8U18yZhWt4j/5XHrwzBo8+p/0bI=
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in unique_attributes.gemspec
4
+ gemspec
@@ -0,0 +1,22 @@
1
+ Copyright (c) 2015 Panorama Education
2
+
3
+ MIT License
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining
6
+ a copy of this software and associated documentation files (the
7
+ "Software"), to deal in the Software without restriction, including
8
+ without limitation the rights to use, copy, modify, merge, publish,
9
+ distribute, sublicense, and/or sell copies of the Software, and to
10
+ permit persons to whom the Software is furnished to do so, subject to
11
+ the following conditions:
12
+
13
+ The above copyright notice and this permission notice shall be
14
+ included in all copies or substantial portions of the Software.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17
+ EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18
+ MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19
+ NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20
+ LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21
+ OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22
+ WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
@@ -0,0 +1,113 @@
1
+ [![Code Climate](https://codeclimate.com/github/panorama-ed/unique_attributes/badges/gpa.svg)](https://codeclimate.com/github/panorama-ed/unique_attributes) [![Test Coverage](https://codeclimate.com/github/panorama-ed/unique_attributes/badges/coverage.svg)](https://codeclimate.com/github/panorama-ed/unique_attributes) [![Inline docs](http://inch-ci.org/github/panorama-ed/unique_attributes.png)](http://inch-ci.org/github/panorama-ed/unique_attributes) [![Build Status](https://travis-ci.org/panorama-ed/unique_attributes.svg)](https://travis-ci.org/panorama-ed/unique_attributes)
2
+
3
+ # UniqueAttributes
4
+
5
+ UniqueAttributes gives you an easy way to ensure that autogenerated fields on
6
+ your ActiveRecord models are unique.
7
+
8
+ Auto-assign usernames for your users? You've come to the right place.
9
+
10
+ ## Installation
11
+
12
+ Add this line to your application's Gemfile:
13
+
14
+ ```ruby
15
+ gem 'unique_attributes'
16
+ ```
17
+
18
+ And then execute:
19
+
20
+ $ bundle
21
+
22
+ Or install it yourself as:
23
+
24
+ $ gem install unique_attributes
25
+
26
+ ## Usage
27
+
28
+ ```ruby
29
+ require "unique_attributes"
30
+
31
+ class User < ActiveRecord::Base
32
+ include UniqueAttributes
33
+
34
+ unique_attribute :username, proc { SecureRandom.hex }
35
+ end
36
+ ```
37
+
38
+ Voilà! Now let's see how it works:
39
+
40
+ ```ruby
41
+ > user = User.new
42
+ > user.username
43
+ => nil
44
+ > user.save!
45
+ > user.username
46
+ => "1a4523822c1a2bebdfc0c036c94f1e0e"
47
+ ```
48
+
49
+ Your user now has a username that's automatically set via the proc you specify,
50
+ and it's guaranteed to be unique among all users.
51
+
52
+ You can still change the value at any time:
53
+ ```ruby
54
+ > user.username = "Grace Hopper"
55
+ > user.save!
56
+ > user.username
57
+ => "Grace Hopper"
58
+ ```
59
+
60
+ What if the uniqueness is scoped by something? No problem:
61
+ ```ruby
62
+ unique_attribute :username, proc { SecureRandom.hex }, scope: :group_id
63
+ ```
64
+
65
+ You can pass in any scopes you could pass into a Rails uniqueness validation.
66
+ Now:
67
+ ```ruby
68
+ > user1 = User.new(group_id: 1)
69
+ > user2 = User.new(group_id: 1)
70
+ > user3 = User.new(group_id: 2)
71
+ ```
72
+
73
+ Because `user1` and `user2` are in the same uniqueness scope, we are guaranteed
74
+ to give them different usernames. `user3` could have the same username as either
75
+ of them since it's outside the uniqueness scope.
76
+
77
+ -----
78
+
79
+ **Note that UniqueAttributes assumes you have an accompanying unique
80
+ index in your database:**
81
+ ```ruby
82
+ add_index :users, :username, unique: true
83
+ ```
84
+
85
+ or, in the case of a scoped uniqueness:
86
+ ```ruby
87
+ add_index :users, [:username, :group_id], unique: true
88
+ ```
89
+
90
+ ## Database Compatibility
91
+
92
+ UniqueAttributes currently supports **PostgreSQL** and **SQLite3**, though
93
+ adding support for your favorite database adapter is as easy as writing a regex
94
+ to parse its uniqueness violation error messages. (Note that MySQL's messages do
95
+ not give granular enough output and thus are not supported currently. Maybe you
96
+ can come up with a fix?)
97
+
98
+ ## Contributing
99
+
100
+ 1. Fork it (https://github.com/panorama-ed/unique_attributes/fork)
101
+ 2. Create your feature branch (`git checkout -b my-new-feature`)
102
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
103
+ 4. Push to the branch (`git push origin my-new-feature`)
104
+ 5. Create a new Pull Request
105
+
106
+ **Make sure your changes have appropriate tests (`bundle exec rspec`)
107
+ and conform to the Rubocop style specified.** We use
108
+ [overcommit](https://github.com/causes/overcommit) to enforce good code.
109
+
110
+ ## License
111
+
112
+ UniqueAttributes is released under the
113
+ [MIT License](https://github.com/panorama-ed/unique_attributes/blob/master/LICENSE.txt).
@@ -0,0 +1 @@
1
+ require "bundler/gem_tasks"
@@ -0,0 +1,106 @@
1
+ require "unique_attributes/version"
2
+
3
+ require "active_support/concern"
4
+
5
+ # UniqueAttributes provides the unique_attribute method to assign a unique
6
+ # attribute to the given model, using the passed block.
7
+
8
+ # Example: unique_attribute :code { SecureRandom.random_number(1000) }
9
+
10
+ module UniqueAttributes
11
+ extend ActiveSupport::Concern
12
+
13
+ # If we try saving an object 50 times and it fails each time, raise an error.
14
+ # This should be high enough to handle even fairly collision-prone attribute
15
+ # generation algorithms.
16
+ SAVE_ATTEMPTS_LIMIT = 50
17
+
18
+ included do
19
+ class_attribute :unique_attributes
20
+ self.unique_attributes = Hash.new
21
+
22
+ # Indicate that a given attribute is unique and should be auto-assigned with
23
+ # the given block.
24
+ # @param name [Symbol] the name of the ActiveRecord attribute
25
+ # @param block [Proc] the code to use to auto-assign the attribute
26
+ # @param scope the scope to limit uniqueness by for the attribute; uses the
27
+ # same format as Rails' `validates *, uniqueness: { scope: __ }` pattern.
28
+ def self.unique_attribute(name, block, scope: nil)
29
+ unique_attributes[name] = block # Store the proc for this attribute.
30
+
31
+ # Use a uniqueness scope if one is passed; otherwise have global
32
+ # uniqueness.
33
+ uniqueness_options = scope ? { scope: scope } : true
34
+
35
+ # Note: This is restricted to update only since the attribute value is not
36
+ # generated until we save the model the first time. The around_save
37
+ # callback happens after validation, but before saving, so we need to make
38
+ # it past validation at least one time before checking for a valid code.
39
+ validates name, uniqueness: uniqueness_options, on: :update
40
+ validates name, presence: true, on: :update
41
+
42
+ # Assign all unique attributes when saving.
43
+ # Note that even if we call unique_attribute more than once within a
44
+ # class, Rails only runs this around_save logic once per save, so we
45
+ # therefore need the around_save logic to handle *all* unique attributes
46
+ # (not just the one defined in this method).
47
+ around_save :save_with_unique_attributes
48
+ end
49
+
50
+ private
51
+
52
+ # @return [Hash] the subset of the unique attributes hash for which we have
53
+ # no values set.
54
+ def blank_unique_attributes
55
+ self.class.unique_attributes.select { |k| send(k).nil? }
56
+ end
57
+
58
+ # Ensures that the attribute value exists and is unique (relying on a
59
+ # database-level unique index) when saving. This will set the value on the
60
+ # first save of the object.
61
+ def save_with_unique_attributes
62
+ blank_attrs = blank_unique_attributes
63
+
64
+ # If we have blank unique attributes.
65
+ if blank_attrs.size > 0
66
+ attempts = 0
67
+
68
+ # Keep retrying until the save works.
69
+ while !self.persisted?
70
+ attempts += 1 # Keep track of the number of times we've tried to save.
71
+
72
+ # Set each of the blank attributes with the given blocks.
73
+ blank_attrs.each { |attr, block| write_attribute(attr, block.call) }
74
+
75
+ begin
76
+ ActiveRecord::Base.transaction(requires_new: true) do
77
+ yield # Perform the save, and see if it works.
78
+ end
79
+ rescue ActiveRecord::RecordNotUnique => error
80
+ attr_group = "(?<attr>#{blank_attrs.keys.join('|')})"
81
+ other_fields = "(, [\\w`'\"]+)*"
82
+ sqlite3_regex = /column(s)? #{attr_group}#{other_fields} (is|are) not unique/
83
+ postgresql_regex = /Key \(#{attr_group}#{other_fields}\)=\([\w\s,]*\) already exists/
84
+
85
+ match = sqlite3_regex.match(error.message) ||
86
+ postgresql_regex.match(error.message)
87
+
88
+ # If we've managed to hit the same unique attribute of a record
89
+ # already in the database, then we should wipe the attribute and try
90
+ # again, unless we've already done this many times in which case we
91
+ # should let the error bubble up.
92
+ if match && attempts <= SAVE_ATTEMPTS_LIMIT
93
+ attr = match[:attr].to_sym
94
+ blank_attrs = { attr => blank_attrs[attr] }
95
+ write_attribute(attr, nil)
96
+ else
97
+ raise error # If something else went wrong, let it propagate.
98
+ end
99
+ end
100
+ end
101
+ else # If the unique values are already set, perform a regular save.
102
+ yield
103
+ end
104
+ end
105
+ end
106
+ end
@@ -0,0 +1,3 @@
1
+ module UniqueAttributes
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,9 @@
1
+ sqlite3_test:
2
+ adapter: sqlite3
3
+ database: ":memory:"
4
+ timeout: 500
5
+
6
+ postgresql_test:
7
+ adapter: postgresql
8
+ database: unique_attributes_test
9
+ username: postgres
@@ -0,0 +1,38 @@
1
+ class TestSetupMigration < ActiveRecord::Migration
2
+ def up
3
+ return if ActiveRecord::Base.connection.table_exists? :test_classes
4
+
5
+ create_table :test_classes do |t|
6
+ t.string :autogenerated_username
7
+ t.string :other_field, null: false
8
+ end
9
+ add_index :test_classes, :autogenerated_username, unique: true
10
+ add_index :test_classes, :other_field, unique: true
11
+
12
+ create_table :scoped_test_classes do |t|
13
+ t.string :autogenerated_username
14
+ t.string :other_field
15
+ end
16
+ add_index :scoped_test_classes,
17
+ [:autogenerated_username, :other_field],
18
+ unique: true,
19
+ name: :scoped_uniq_indx
20
+
21
+ create_table :multiattribute_test_classes do |t|
22
+ t.string :autogenerated_username
23
+ t.string :autogenerated_password
24
+ end
25
+ add_index :multiattribute_test_classes,
26
+ :autogenerated_username,
27
+ unique: true
28
+ add_index :multiattribute_test_classes,
29
+ :autogenerated_password,
30
+ unique: true
31
+ end
32
+
33
+ def down
34
+ drop_table :test_classes
35
+ drop_table :scoped_test_classes
36
+ drop_table :multiattribute_test_classes
37
+ end
38
+ end
@@ -0,0 +1,15 @@
1
+ require "spec_helper"
2
+ require "shared/unique_attributes_examples"
3
+
4
+ RSpec.describe "PostgreSQL" do
5
+ before :all do
6
+ ActiveRecord::Base.establish_connection(:postgresql_test)
7
+ TestSetupMigration.migrate(:up)
8
+ end
9
+
10
+ include_examples ".unique_attribute"
11
+
12
+ after :all do
13
+ ActiveRecord::Base.remove_connection
14
+ end
15
+ end
@@ -0,0 +1,113 @@
1
+ require "spec_helper"
2
+
3
+ require "support/multiattribute_test_class"
4
+ require "support/scoped_test_class"
5
+ require "support/test_class"
6
+
7
+ RSpec.shared_examples ".unique_attribute" do
8
+ let(:obj1) { TestClass.new(other_field: "Foo") }
9
+ let(:obj2) { TestClass.new(other_field: "Bar") }
10
+
11
+ it "generates a value when saving" do
12
+ obj1.save!
13
+ expect(obj1.autogenerated_username).to_not be_nil
14
+ end
15
+
16
+ it "does not overwrite a value that is manually set" do
17
+ obj1.autogenerated_username = "Dummy"
18
+ expect(obj1.autogenerated_username).to eq "Dummy"
19
+ end
20
+
21
+ it "does not generate a new value when saved multiple times" do
22
+ obj1.save!
23
+ val = obj1.autogenerated_username
24
+
25
+ obj1.other_field = "A" # Set another field to force the object to save.
26
+ obj1.save!
27
+
28
+ # Check that the autogenerated field doesn't change.
29
+ expect(obj1.autogenerated_username).to eq val
30
+ end
31
+
32
+ it "generates a new value if the one generated is already taken" do
33
+ allow(TestClass).to receive(:generate_username).and_return("1", "1", "2")
34
+
35
+ obj1.save!
36
+ obj2.save!
37
+
38
+ expect(obj1.autogenerated_username).to eq "1"
39
+ expect(obj2.autogenerated_username).to eq "2"
40
+ end
41
+
42
+ it "raises an error if updated to an existing one" do
43
+ obj1.save!
44
+ obj2.save!
45
+
46
+ # Update obj2's value to obj1's to create a uniqueness collision.
47
+ obj2.autogenerated_username = obj1.autogenerated_username
48
+
49
+ expect { obj2.save! }.to raise_error(ActiveRecord::RecordInvalid)
50
+ end
51
+
52
+ it "respects the scope argument" do
53
+ allow(ScopedTestClass).to receive(:generate_username).
54
+ and_return("1", "1", "1", "1", "2")
55
+
56
+ obj1 = ScopedTestClass.create!(other_field: "A")
57
+ obj2 = ScopedTestClass.create!(other_field: "B")
58
+ obj3 = ScopedTestClass.create!(other_field: "A")
59
+
60
+ expect(obj1.autogenerated_username).to eq "1"
61
+ expect(obj2.autogenerated_username).to eq "1"
62
+ expect(obj3.autogenerated_username).to eq "2"
63
+ end
64
+
65
+ it "does not retry the save when an unrelated uniqueness violation occurs" do
66
+ expect(TestClass).to receive(:generate_username).
67
+ exactly(2).times.
68
+ and_call_original
69
+
70
+ obj1.save!
71
+ obj2.other_field = obj1.other_field
72
+
73
+ # This will raise an error because a database unique index ensures that
74
+ # other_field is unique.
75
+ expect { obj2.save! }.to raise_error(ActiveRecord::RecordNotUnique)
76
+ end
77
+
78
+ it "raises the error when an unrelated non-uniqueness error occurs" do
79
+ obj1.other_field = nil
80
+
81
+ # This will raise an error because a database constraint ensures that
82
+ # other_field is not NULL.
83
+ expect { obj1.save! }.to raise_error(ActiveRecord::StatementInvalid)
84
+ end
85
+
86
+ it "raises the unique violation error if we've tried saving too many times" do
87
+ # Stub out the username generation function to always cause collisions.
88
+ allow(TestClass).to receive(:generate_username).and_return("1")
89
+
90
+ obj1.save!
91
+
92
+ # After retrying the save many times, we will eventually raise an error.
93
+ expect { obj2.save! }.to raise_error(ActiveRecord::RecordNotUnique)
94
+ end
95
+
96
+ context "when model has multiple unique_attribute fields" do
97
+ it "only retries fields as needed" do
98
+ # We stub the username/password generation such that the first two
99
+ # usernames generated collide but the passwords do not. We use
100
+ # expectations to ensure that the username is re-generated but the
101
+ # password is not.
102
+ expect(MultiattributeTestClass).to receive(:generate_username).
103
+ exactly(3).times.
104
+ and_return("1", "1", "2")
105
+ expect(MultiattributeTestClass).to receive(:generate_password).
106
+ exactly(2).times.
107
+ and_return("A", "B")
108
+
109
+ MultiattributeTestClass.create!
110
+ MultiattributeTestClass.create!
111
+ end
112
+ end
113
+ end
@@ -0,0 +1,55 @@
1
+ require "codeclimate-test-reporter"
2
+ CodeClimate::TestReporter.start
3
+
4
+ require "active_record"
5
+ require "database_cleaner"
6
+
7
+ require "unique_attributes"
8
+
9
+ ActiveRecord::Base.configurations = YAML.load_file("spec/config/database.yml")
10
+
11
+ RSpec.configure do |config|
12
+ # These two settings work together to allow you to limit a spec run
13
+ # to individual examples or groups you care about by tagging them with
14
+ # `:focus` metadata. When nothing is tagged with `:focus`, all examples
15
+ # get run.
16
+ config.filter_run :focus
17
+ config.run_all_when_everything_filtered = true
18
+
19
+ # Roll back the changes to the database after each test.
20
+ config.around(:each) do |example|
21
+ DatabaseCleaner.cleaning do
22
+ example.run
23
+ end
24
+ end
25
+
26
+ # Limits the available syntax to the non-monkey patched syntax that is
27
+ # recommended.
28
+ # For more details, see:
29
+ # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
30
+ # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
31
+ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
32
+ config.disable_monkey_patching!
33
+
34
+ # Many RSpec users commonly either run the entire suite or an individual
35
+ # file, and it's useful to allow more verbose output when running an
36
+ # individual spec file.
37
+ if config.files_to_run.one?
38
+ # Use the documentation formatter for detailed output,
39
+ # unless a formatter has already been configured
40
+ # (e.g. via a command-line flag).
41
+ config.default_formatter = "doc"
42
+ end
43
+
44
+ # Run specs in random order to surface order dependencies. If you find an
45
+ # order dependency and want to debug it, you can fix the order by providing
46
+ # the seed, which is printed after each run.
47
+ # --seed 1234
48
+ config.order = :random
49
+
50
+ # Seed global randomization in this process using the `--seed` CLI option.
51
+ # Setting this allows you to use `--seed` to deterministically reproduce
52
+ # test failures related to randomization by passing the same `--seed` value
53
+ # as the one that triggered the failure.
54
+ Kernel.srand config.seed
55
+ end
@@ -0,0 +1,16 @@
1
+ require "spec_helper"
2
+ require "shared/unique_attributes_examples"
3
+ require "config/test_setup_migration"
4
+
5
+ RSpec.describe "SQLite3" do
6
+ before :all do
7
+ ActiveRecord::Base.establish_connection(:sqlite3_test)
8
+ TestSetupMigration.migrate(:up)
9
+ end
10
+
11
+ include_examples ".unique_attribute"
12
+
13
+ after :all do
14
+ ActiveRecord::Base.remove_connection
15
+ end
16
+ end
@@ -0,0 +1,13 @@
1
+ class MultiattributeTestClass < ActiveRecord::Base
2
+ include UniqueAttributes
3
+ unique_attribute :autogenerated_username, proc { generate_username }
4
+ unique_attribute :autogenerated_password, proc { generate_password }
5
+
6
+ def self.generate_username
7
+ SecureRandom.hex
8
+ end
9
+
10
+ def self.generate_password
11
+ SecureRandom.hex
12
+ end
13
+ end
@@ -0,0 +1,10 @@
1
+ class ScopedTestClass < ActiveRecord::Base
2
+ include UniqueAttributes
3
+ unique_attribute :autogenerated_username,
4
+ proc { generate_username },
5
+ scope: :other_field
6
+
7
+ def self.generate_username
8
+ SecureRandom.hex
9
+ end
10
+ end
@@ -0,0 +1,8 @@
1
+ class TestClass < ActiveRecord::Base
2
+ include UniqueAttributes
3
+ unique_attribute :autogenerated_username, proc { generate_username }
4
+
5
+ def self.generate_username
6
+ SecureRandom.hex
7
+ end
8
+ end
@@ -0,0 +1,4 @@
1
+ # Instead of defining specs here, we define them in
2
+ # shared/unique_attributes_examples.rb. We then have a different spec file for
3
+ # each supported database adapter, whch runs the shared RSpec tests found in
4
+ # the shared/unique_attributes_examples.rb file.
@@ -0,0 +1,35 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path("../lib", __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require "unique_attributes/version"
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "unique_attributes"
8
+ spec.version = UniqueAttributes::VERSION
9
+ spec.authors = ["Jacob Evelyn"]
10
+ spec.email = ["jevelyn@panoramaed.com"]
11
+ spec.summary = "Auto-assign unique attributes for ActiveRecord objects."
12
+ spec.description = "Easily set ActiveRecord attributes to auto-generate "\
13
+ "as unique values from a given proc."
14
+ spec.homepage = "https://www.github.com/panorama-ed/unique_attributes"
15
+ spec.license = "MIT"
16
+
17
+ spec.files = `git ls-files -z`.split("\x0")
18
+ spec.executables = spec.files.grep(%r{^bin/}) { |f| File.basename(f) }
19
+ spec.test_files = spec.files.grep(%r{^(test|spec|features)/})
20
+ spec.require_paths = ["lib"]
21
+
22
+ spec.add_dependency "activerecord", "~> 4.0"
23
+ spec.add_dependency "activesupport", "~> 4.0"
24
+
25
+ spec.add_development_dependency "bundler", "~> 1.7"
26
+ spec.add_development_dependency "codeclimate-test-reporter", "~> 0.4"
27
+ spec.add_development_dependency "database_cleaner", "~> 1.4"
28
+ spec.add_development_dependency "overcommit", "~> 0.21"
29
+ spec.add_development_dependency "pg", "~> 0.18"
30
+ spec.add_development_dependency "rake", "~> 10.0"
31
+ spec.add_development_dependency "rspec", "~> 3.1"
32
+ spec.add_development_dependency "rspec-mocks", "~> 3.1"
33
+ spec.add_development_dependency "rubocop", "~> 0.28"
34
+ spec.add_development_dependency "sqlite3", "~> 1.3"
35
+ end
metadata ADDED
@@ -0,0 +1,244 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: unique_attributes
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Jacob Evelyn
8
+ autorequire:
9
+ bindir: bin
10
+ cert_chain: []
11
+ date: 2015-01-20 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.0'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ~>
25
+ - !ruby/object:Gem::Version
26
+ version: '4.0'
27
+ - !ruby/object:Gem::Dependency
28
+ name: activesupport
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - ~>
32
+ - !ruby/object:Gem::Version
33
+ version: '4.0'
34
+ type: :runtime
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - ~>
39
+ - !ruby/object:Gem::Version
40
+ version: '4.0'
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: codeclimate-test-reporter
57
+ requirement: !ruby/object:Gem::Requirement
58
+ requirements:
59
+ - - ~>
60
+ - !ruby/object:Gem::Version
61
+ version: '0.4'
62
+ type: :development
63
+ prerelease: false
64
+ version_requirements: !ruby/object:Gem::Requirement
65
+ requirements:
66
+ - - ~>
67
+ - !ruby/object:Gem::Version
68
+ version: '0.4'
69
+ - !ruby/object:Gem::Dependency
70
+ name: database_cleaner
71
+ requirement: !ruby/object:Gem::Requirement
72
+ requirements:
73
+ - - ~>
74
+ - !ruby/object:Gem::Version
75
+ version: '1.4'
76
+ type: :development
77
+ prerelease: false
78
+ version_requirements: !ruby/object:Gem::Requirement
79
+ requirements:
80
+ - - ~>
81
+ - !ruby/object:Gem::Version
82
+ version: '1.4'
83
+ - !ruby/object:Gem::Dependency
84
+ name: overcommit
85
+ requirement: !ruby/object:Gem::Requirement
86
+ requirements:
87
+ - - ~>
88
+ - !ruby/object:Gem::Version
89
+ version: '0.21'
90
+ type: :development
91
+ prerelease: false
92
+ version_requirements: !ruby/object:Gem::Requirement
93
+ requirements:
94
+ - - ~>
95
+ - !ruby/object:Gem::Version
96
+ version: '0.21'
97
+ - !ruby/object:Gem::Dependency
98
+ name: pg
99
+ requirement: !ruby/object:Gem::Requirement
100
+ requirements:
101
+ - - ~>
102
+ - !ruby/object:Gem::Version
103
+ version: '0.18'
104
+ type: :development
105
+ prerelease: false
106
+ version_requirements: !ruby/object:Gem::Requirement
107
+ requirements:
108
+ - - ~>
109
+ - !ruby/object:Gem::Version
110
+ version: '0.18'
111
+ - !ruby/object:Gem::Dependency
112
+ name: rake
113
+ requirement: !ruby/object:Gem::Requirement
114
+ requirements:
115
+ - - ~>
116
+ - !ruby/object:Gem::Version
117
+ version: '10.0'
118
+ type: :development
119
+ prerelease: false
120
+ version_requirements: !ruby/object:Gem::Requirement
121
+ requirements:
122
+ - - ~>
123
+ - !ruby/object:Gem::Version
124
+ version: '10.0'
125
+ - !ruby/object:Gem::Dependency
126
+ name: rspec
127
+ requirement: !ruby/object:Gem::Requirement
128
+ requirements:
129
+ - - ~>
130
+ - !ruby/object:Gem::Version
131
+ version: '3.1'
132
+ type: :development
133
+ prerelease: false
134
+ version_requirements: !ruby/object:Gem::Requirement
135
+ requirements:
136
+ - - ~>
137
+ - !ruby/object:Gem::Version
138
+ version: '3.1'
139
+ - !ruby/object:Gem::Dependency
140
+ name: rspec-mocks
141
+ requirement: !ruby/object:Gem::Requirement
142
+ requirements:
143
+ - - ~>
144
+ - !ruby/object:Gem::Version
145
+ version: '3.1'
146
+ type: :development
147
+ prerelease: false
148
+ version_requirements: !ruby/object:Gem::Requirement
149
+ requirements:
150
+ - - ~>
151
+ - !ruby/object:Gem::Version
152
+ version: '3.1'
153
+ - !ruby/object:Gem::Dependency
154
+ name: rubocop
155
+ requirement: !ruby/object:Gem::Requirement
156
+ requirements:
157
+ - - ~>
158
+ - !ruby/object:Gem::Version
159
+ version: '0.28'
160
+ type: :development
161
+ prerelease: false
162
+ version_requirements: !ruby/object:Gem::Requirement
163
+ requirements:
164
+ - - ~>
165
+ - !ruby/object:Gem::Version
166
+ version: '0.28'
167
+ - !ruby/object:Gem::Dependency
168
+ name: sqlite3
169
+ requirement: !ruby/object:Gem::Requirement
170
+ requirements:
171
+ - - ~>
172
+ - !ruby/object:Gem::Version
173
+ version: '1.3'
174
+ type: :development
175
+ prerelease: false
176
+ version_requirements: !ruby/object:Gem::Requirement
177
+ requirements:
178
+ - - ~>
179
+ - !ruby/object:Gem::Version
180
+ version: '1.3'
181
+ description: Easily set ActiveRecord attributes to auto-generate as unique values
182
+ from a given proc.
183
+ email:
184
+ - jevelyn@panoramaed.com
185
+ executables: []
186
+ extensions: []
187
+ extra_rdoc_files: []
188
+ files:
189
+ - .gitignore
190
+ - .overcommit.yml
191
+ - .rubocop.yml
192
+ - .travis.yml
193
+ - Gemfile
194
+ - LICENSE.txt
195
+ - README.md
196
+ - Rakefile
197
+ - lib/unique_attributes.rb
198
+ - lib/unique_attributes/version.rb
199
+ - spec/config/database.yml
200
+ - spec/config/test_setup_migration.rb
201
+ - spec/postgresql_spec.rb
202
+ - spec/shared/unique_attributes_examples.rb
203
+ - spec/spec_helper.rb
204
+ - spec/sqlite3_spec.rb
205
+ - spec/support/multiattribute_test_class.rb
206
+ - spec/support/scoped_test_class.rb
207
+ - spec/support/test_class.rb
208
+ - spec/unique_attributes_spec.rb
209
+ - unique_attributes.gemspec
210
+ homepage: https://www.github.com/panorama-ed/unique_attributes
211
+ licenses:
212
+ - MIT
213
+ metadata: {}
214
+ post_install_message:
215
+ rdoc_options: []
216
+ require_paths:
217
+ - lib
218
+ required_ruby_version: !ruby/object:Gem::Requirement
219
+ requirements:
220
+ - - '>='
221
+ - !ruby/object:Gem::Version
222
+ version: '0'
223
+ required_rubygems_version: !ruby/object:Gem::Requirement
224
+ requirements:
225
+ - - '>='
226
+ - !ruby/object:Gem::Version
227
+ version: '0'
228
+ requirements: []
229
+ rubyforge_project:
230
+ rubygems_version: 2.2.2
231
+ signing_key:
232
+ specification_version: 4
233
+ summary: Auto-assign unique attributes for ActiveRecord objects.
234
+ test_files:
235
+ - spec/config/database.yml
236
+ - spec/config/test_setup_migration.rb
237
+ - spec/postgresql_spec.rb
238
+ - spec/shared/unique_attributes_examples.rb
239
+ - spec/spec_helper.rb
240
+ - spec/sqlite3_spec.rb
241
+ - spec/support/multiattribute_test_class.rb
242
+ - spec/support/scoped_test_class.rb
243
+ - spec/support/test_class.rb
244
+ - spec/unique_attributes_spec.rb