with_uid 0.0.1

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: 7d747828b5e3863195c2e917d4200b05beba20a5
4
+ data.tar.gz: febb7d85430c7e84b407c2a464946161881e3b78
5
+ SHA512:
6
+ metadata.gz: d59aeebfed8b0978c04fd6662b5183a2349401e2f8dfe5fae4a8032cfe380870a45db6c90b89e238ca35b836c033b5b6dad6071e6be77e909bfc1756a6d66708
7
+ data.tar.gz: 039e22e97d175a0bee1b98c2498372d0ddf91778b01076ff8d75ad9aeec152a4c4da85d31f05a5dcf56dfd4f0b14c86e7aa10fdcc0f54b2f84fa37562676664c
@@ -0,0 +1,14 @@
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
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --color
2
+ --require spec_helper
@@ -0,0 +1,6 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.1.5
4
+ - 2.2.0
5
+ script: bundle exec rspec spec
6
+ env: CODECLIMATE_REPO_TOKEN=
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in with_uid.gemspec
4
+ gemspec
data/LICENSE ADDED
@@ -0,0 +1,176 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
@@ -0,0 +1,108 @@
1
+ [![Build Status](https://travis-ci.org/SPBTV/with_uid.svg)](https://travis-ci.org/SPBTV/with_uid)
2
+
3
+ # WithUid
4
+
5
+ Generate customizable uid for your ActiveRecord models
6
+
7
+ ## Installation
8
+
9
+ Add this line to your application's Gemfile:
10
+
11
+ ```ruby
12
+ gem 'with_uid'
13
+ ```
14
+
15
+ And then execute:
16
+
17
+ $ bundle
18
+
19
+ Or install it yourself as:
20
+
21
+ $ gem install with_uid
22
+
23
+ ## Usage
24
+
25
+ Add `uid` column to your model:
26
+
27
+ $ rails generate migration AddUidToUser uid:string -s
28
+
29
+ Include WithUid module:
30
+
31
+ ```ruby
32
+ class User < ActiveRecord::Base
33
+ include WithUid
34
+
35
+ generate_uid
36
+ end
37
+ ```
38
+
39
+ This will generate RFC 4122 compatible uid. You may specify
40
+ block to generate `uid` according your own rule. This block
41
+ would be executed in `User` instance context.
42
+
43
+ ```ruby
44
+ class User < ActiveRecord::Base
45
+ include WithUid
46
+
47
+ generate_uid do
48
+ full_name.parameterize
49
+ end
50
+ end
51
+ ```
52
+
53
+ If you want to generate uid based on some `ActiveRecord` attribute
54
+ there is a helper for that:
55
+
56
+ ```ruby
57
+ class Post < ActiveRecord::Base
58
+ include WithUid
59
+
60
+ humanize_uid_with(:title)
61
+ end
62
+ ```
63
+
64
+ If humanized attribute is not uniq it will add some random suffix
65
+ at the end.
66
+
67
+ You can customize suffix as well:
68
+
69
+ ```ruby
70
+ class Post < ActiveRecord::Base
71
+ include WithUid
72
+
73
+ humanize_uid_with(:title, suffix: ->(post) { post.author.uid } )
74
+ end
75
+ ```
76
+
77
+ It's also possible to add prefix to each uid:
78
+
79
+ ```ruby
80
+ class Post < ActiveRecord::Base
81
+ include WithUid
82
+
83
+ generate_uid(prefix: 'post_')
84
+ end
85
+ ```
86
+
87
+ Both `prefix` and `suffix` may be a `String` or a `Proc`.
88
+
89
+
90
+ ## Contributing
91
+
92
+ 1. Fork it ( https://github.com/SPBTV/with_uid/fork )
93
+ 2. Create your feature branch (`git checkout -b feature/my-new-feature`)
94
+ 3. Commit your changes (`git commit -am 'Add some feature'`)
95
+ 4. Push to the branch (`git push origin feature/my-new-feature`)
96
+ 5. Create a new Pull Request
97
+
98
+ ##License
99
+
100
+ Copyright 2014 SPB TV AG
101
+
102
+ Licensed under the Apache License, Version 2.0 (the ["License"](LICENSE)); you may not use this file except in compliance with the License.
103
+
104
+ You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)
105
+
106
+ Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
107
+
108
+ See the License for the specific language governing permissions and limitations under the License.
@@ -0,0 +1 @@
1
+ require 'bundler/gem_tasks'
@@ -0,0 +1,137 @@
1
+ require 'active_support/concern'
2
+ require 'securerandom'
3
+ require 'with_uid/version'
4
+ require 'with_uid/uid_generator'
5
+ require 'with_uid/uid_validator'
6
+
7
+ # Allow to generate nice uids for ActiveRecord objects
8
+ #
9
+ module WithUid
10
+ extend ActiveSupport::Concern
11
+
12
+ included do
13
+ validates :uid, presence: true
14
+ validates :uid, uniqueness: true, unless: :skip_uid_uniqueness?
15
+ validates :uid, :'with_uid/uid' => true
16
+ end
17
+
18
+ module ClassMethods
19
+ # Find record by uid
20
+ #
21
+ # @param uid [String]
22
+ # @return [ActiveRecord::Base]
23
+ # @raise [ActiveRecord::RecordNotFound] if no such record
24
+ # @see #find_by!
25
+ #
26
+ def by_uid!(uid)
27
+ find_by!(uid: uid)
28
+ end
29
+
30
+ # Find record by uid
31
+ #
32
+ # @param uid [String]
33
+ # @return [ActiveRecord::Base, nil]
34
+ # @see #find_by
35
+ #
36
+ def by_uid(uid)
37
+ find_by(uid: uid)
38
+ end
39
+
40
+ # Generate uid for given model
41
+ #
42
+ # @yieldreturn [String] generated uid. So you may specify the
43
+ # way of generating uid.
44
+ # @param [Hash]
45
+ # @option options [String, Proc] :prefix ('') prefix for uid
46
+ # inserted for each generated uid.
47
+ # @option options [String, Proc] :suffix (random string) for uid
48
+ # inserted if uid is not uniq.
49
+ # @return [void]
50
+ #
51
+ # @example without block
52
+ # class User < ActiveRecord::Base
53
+ # generate_uid(prefix: ->(user) { user.sex })
54
+ # end
55
+ #
56
+ # @example with block using user's name
57
+ # class User < ActiveRecord::Base
58
+ # generate_uid(prefix: 'user_') do
59
+ # WithUid.format(name)
60
+ # end
61
+ # end
62
+ #
63
+ # If no block given it will generate uid according RFC 4122.
64
+ # You are free to customize this uid with +:prefix+.
65
+ #
66
+ # @example RFC 4122 uid
67
+ # class User < ActiveRecord::Base
68
+ # generate_uid
69
+ # end
70
+ #
71
+ def generate_uid(**options, &block)
72
+ before_validation do
73
+ if block_given?
74
+ generate_uid(**options, &block)
75
+ else
76
+ generate_uid(**options.merge(suffix: '')) do
77
+ SecureRandom.uuid
78
+ end
79
+ end
80
+ end
81
+ end
82
+
83
+ # Generate uid using record's attribute
84
+ #
85
+ # @param attr [Symbol] attribute name
86
+ # @param options [Hash] @see #generate_uid
87
+ # @return [void]
88
+ #
89
+ # @example
90
+ # class User < ActiveRecord::Base
91
+ # humanize_uid_with(:name, prefix: 'user_')
92
+ # end
93
+ # user = User.create(name: 'Tema Bolshakov')
94
+ # user.uid #=> "tema_bolshakov"
95
+ #
96
+ def humanize_uid_with(attr, **options)
97
+ generate_uid(**options) do
98
+ value = send(attr)
99
+ WithUid.format(value) if value.present?
100
+ end
101
+ end
102
+ end
103
+
104
+ # If you are not interested in uid uniqeness
105
+ # redefine this method in your model
106
+ # @example
107
+ # class User < ActiveRecord::Base
108
+ # humanize_uid_with(:name, prefix: 'user_')
109
+ #
110
+ # def skip_uid_uniqueness?
111
+ # true
112
+ # end
113
+ # end
114
+ #
115
+ def skip_uid_uniqueness?
116
+ false
117
+ end
118
+
119
+ def self.format(str)
120
+ I18n.transliterate(str.to_s).parameterize
121
+ end
122
+
123
+ # @api private
124
+ def generate_uid(**options, &block)
125
+ fail LocalJumpError, 'no block given' unless block_given?
126
+ return if uid.present?
127
+
128
+ self.uid = uid_generator(**options, &block).detect do |uid|
129
+ !self.class.exists?(uid: uid)
130
+ end
131
+ end
132
+
133
+ # @api private
134
+ def uid_generator(**options, &block)
135
+ UidGenerator.new(self, **options, &block)
136
+ end
137
+ end
@@ -0,0 +1,55 @@
1
+ require 'active_support/core_ext/object/blank'
2
+
3
+ module WithUid
4
+ # @api private
5
+ class UidGenerator
6
+ include Enumerable
7
+
8
+ attr_reader :context, :generator
9
+
10
+ def initialize(context, ** options, &generator)
11
+ @context = context
12
+ @generator = generator
13
+ @suffix = options[:suffix]
14
+ @prefix = options[:prefix]
15
+ end
16
+
17
+ def each
18
+ return enum_for(:each) unless block_given?
19
+
20
+ yield uid(prefix)
21
+ loop do
22
+ next_uid = uid(prefix, suffix)
23
+ yield next_uid
24
+ end
25
+ end
26
+
27
+ def suffix
28
+ with_default(@suffix) do
29
+ "_#{SecureRandom.hex(3)}"
30
+ end
31
+ end
32
+
33
+ def prefix
34
+ with_default(@prefix) do
35
+ ''
36
+ end
37
+ end
38
+
39
+ private
40
+
41
+ def uid(prefix, suffix = nil)
42
+ [prefix, context.instance_eval(&generator), suffix].join
43
+ end
44
+
45
+ def with_default(value)
46
+ if value.respond_to?(:call)
47
+ value.call(context)
48
+ elsif value.nil?
49
+ yield
50
+ else
51
+ value
52
+ end
53
+ end
54
+ end
55
+ end
@@ -0,0 +1,21 @@
1
+ require 'active_model/validator'
2
+
3
+ module WithUid
4
+ # Validates uid
5
+ # @example required uid
6
+ # validates :id, 'with_uid/uid' => true
7
+ #
8
+ # @example optional uid
9
+ # validates :id, 'with_uid/uid' => { }allow_blank: true }
10
+ #
11
+ class UidValidator < ActiveModel::EachValidator
12
+ REGEX = /\A[0-9a-z\-_\.]+\z/i
13
+
14
+ def validate_each(record, attribute, value)
15
+ return if options.fetch(:allow_blank, false) && value.blank?
16
+ return if value =~ REGEX
17
+
18
+ record.errors[attribute] << options.fetch(:message, 'invalid format')
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,3 @@
1
+ module WithUid
2
+ VERSION = '0.0.1'
3
+ end
@@ -0,0 +1,90 @@
1
+ # This file was generated by the `rspec --init` command. Conventionally, all
2
+ # specs live under a `spec` directory, which RSpec adds to the `$LOAD_PATH`.
3
+ # The generated `.rspec` file contains `--require spec_helper` which will cause
4
+ # this file to always be loaded, without a need to explicitly require it in any
5
+ # files.
6
+ #
7
+ # Given that it is always loaded, you are encouraged to keep this file as
8
+ # light-weight as possible. Requiring heavyweight dependencies from this file
9
+ # will add to the boot time of your test suite on EVERY test run, even for an
10
+ # individual file that may not need all of that loaded. Instead, consider making
11
+ # a separate helper file that requires the additional dependencies and performs
12
+ # the additional setup, and require it from the spec files that actually need
13
+ # it.
14
+ #
15
+ # The `.rspec` file also contains a few flags that are not defaults but that
16
+ # users commonly want.
17
+ #
18
+ # See http://rubydoc.info/gems/rspec-core/RSpec/Core/Configuration
19
+ RSpec.configure do |config|
20
+ # rspec-expectations config goes here. You can use an alternate
21
+ # assertion/expectation library such as wrong or the stdlib/minitest
22
+ # assertions if you prefer.
23
+ config.expect_with :rspec do |expectations|
24
+ # This option will default to `true` in RSpec 4. It makes the `description`
25
+ # and `failure_message` of custom matchers include text for helper methods
26
+ # defined using `chain`, e.g.:
27
+ # be_bigger_than(2).and_smaller_than(4).description
28
+ # # => "be bigger than 2 and smaller than 4"
29
+ # ...rather than:
30
+ # # => "be bigger than 2"
31
+ expectations.include_chain_clauses_in_custom_matcher_descriptions = true
32
+ end
33
+
34
+ # rspec-mocks config goes here. You can use an alternate test double
35
+ # library (such as bogus or mocha) by changing the `mock_with` option here.
36
+ config.mock_with :rspec do |mocks|
37
+ # Prevents you from mocking or stubbing a method that does not exist on
38
+ # a real object. This is generally recommended, and will default to
39
+ # `true` in RSpec 4.
40
+ mocks.verify_partial_doubles = true
41
+ end
42
+
43
+ # The settings below are suggested to provide a good initial experience
44
+ # with RSpec, but feel free to customize to your heart's content.
45
+
46
+ # These two settings work together to allow you to limit a spec run
47
+ # to individual examples or groups you care about by tagging them with
48
+ # `:focus` metadata. When nothing is tagged with `:focus`, all examples
49
+ # get run.
50
+ config.filter_run :focus
51
+ config.run_all_when_everything_filtered = true
52
+
53
+ # Limits the available syntax to the non-monkey patched syntax that is
54
+ # recommended. For more details, see:
55
+ # - http://myronmars.to/n/dev-blog/2012/06/rspecs-new-expectation-syntax
56
+ # - http://teaisaweso.me/blog/2013/05/27/rspecs-new-message-expectation-syntax/
57
+ # - http://myronmars.to/n/dev-blog/2014/05/notable-changes-in-rspec-3#new__config_option_to_disable_rspeccore_monkey_patching
58
+ config.disable_monkey_patching!
59
+
60
+ # This setting enables warnings. It's recommended, but in some cases may
61
+ # be too noisy due to issues in dependencies.
62
+ config.warnings = true
63
+
64
+ # Many RSpec users commonly either run the entire suite or an individual
65
+ # file, and it's useful to allow more verbose output when running an
66
+ # individual spec file.
67
+ if config.files_to_run.one?
68
+ # Use the documentation formatter for detailed output,
69
+ # unless a formatter has already been configured
70
+ # (e.g. via a command-line flag).
71
+ config.default_formatter = 'doc'
72
+ end
73
+
74
+ # Print the 10 slowest examples and example groups at the
75
+ # end of the spec run, to help surface which specs are running
76
+ # particularly slow.
77
+ config.profile_examples = 10
78
+
79
+ # Run specs in random order to surface order dependencies. If you find an
80
+ # order dependency and want to debug it, you can fix the order by providing
81
+ # the seed, which is printed after each run.
82
+ # --seed 1234
83
+ config.order = :random
84
+
85
+ # Seed global randomization in this process using the `--seed` CLI option.
86
+ # Setting this allows you to use `--seed` to deterministically reproduce
87
+ # test failures related to randomization by passing the same `--seed` value
88
+ # as the one that triggered the failure.
89
+ Kernel.srand config.seed
90
+ end
@@ -0,0 +1,18 @@
1
+ require 'active_record'
2
+ require 'with_uid'
3
+
4
+ ActiveRecord::Base.establish_connection(
5
+ adapter: 'sqlite3',
6
+ database: ':memory:'
7
+ )
8
+ ActiveRecord::Base.connection
9
+ .create_table('model_with_uids', temporary: true) do |t|
10
+ t.string :name, :uid
11
+ end
12
+
13
+ class ModelWithUid < ActiveRecord::Base
14
+ self.primary_key = :id
15
+ include WithUid
16
+
17
+ generate_uid
18
+ end
@@ -0,0 +1,89 @@
1
+ require 'spec_helper'
2
+ require 'with_uid/uid_generator'
3
+ require 'ostruct'
4
+
5
+ RSpec.describe WithUid::UidGenerator do
6
+ let(:name) { 'The name' }
7
+ let(:suffix) { '_suffix' }
8
+ let(:prefix) { 'prefix_' }
9
+ let(:binding) do
10
+ OpenStruct.new(name: name)
11
+ end
12
+
13
+ def generator(**options)
14
+ WithUid::UidGenerator.new(binding, **options) do
15
+ "#{name}-42"
16
+ end
17
+ end
18
+
19
+ context 'yielding' do
20
+ it 'yield uids' do
21
+ uids = generator(prefix: prefix, suffix: suffix).each
22
+ uid_from_block = uids.next
23
+ uid_with_suffix = uids.next
24
+
25
+ expect(uid_from_block).to eq "#{prefix}#{name}-42"
26
+ expect(uid_with_suffix).to eq "#{prefix}#{name}-42#{suffix}"
27
+ end
28
+
29
+ it 'yield uids without prefix' do
30
+ uids = generator(suffix: suffix).each
31
+ uid_from_block = uids.next
32
+ uid_with_suffix = uids.next
33
+
34
+ expect(uid_from_block).to eq "#{name}-42"
35
+ expect(uid_with_suffix).to eq "#{name}-42#{suffix}"
36
+ end
37
+
38
+ it 'with empty suffix' do
39
+ uids = generator(suffix: '').each
40
+ uid_from_block = uids.next
41
+ uid_with_suffix = uids.next
42
+
43
+ expect(uid_from_block).to eq "#{name}-42"
44
+ expect(uid_with_suffix).to eq "#{name}-42"
45
+ end
46
+ end
47
+
48
+ describe '#suffix' do
49
+ it 'default value is nil' do
50
+ suffix = generator.suffix
51
+
52
+ expect(suffix.size).to eq(7)
53
+ end
54
+
55
+ it 'default value is callable' do
56
+ suffix_generator = ->(context) { "#{context.name}:foo_bar" }
57
+ suffix = generator(suffix: suffix_generator).suffix
58
+
59
+ expect(suffix).to eq 'The name:foo_bar'
60
+ end
61
+
62
+ it 'default value' do
63
+ suffix = generator(suffix: '32').suffix
64
+
65
+ expect(suffix).to eq '32'
66
+ end
67
+ end
68
+
69
+ describe '#prefix' do
70
+ it 'default value is nil' do
71
+ prefix = generator.prefix
72
+
73
+ expect(prefix).to eq('')
74
+ end
75
+
76
+ it 'default value is callable' do
77
+ prefix_generator = ->(context) { "#{context.name}:foo_bar" }
78
+ prefix = generator(prefix: prefix_generator).prefix
79
+
80
+ expect(prefix).to eq 'The name:foo_bar'
81
+ end
82
+
83
+ it 'default value' do
84
+ prefix = generator(prefix: '32').prefix
85
+
86
+ expect(prefix).to eq '32'
87
+ end
88
+ end
89
+ end
@@ -0,0 +1,75 @@
1
+ require 'spec_helper'
2
+ require 'ostruct'
3
+ require 'with_uid'
4
+ require 'active_model'
5
+
6
+ RSpec.describe WithUid::UidValidator do
7
+ ModelWithRequiredUid = Struct.new(:uid) do
8
+ include ActiveModel::Model
9
+ include ActiveModel::Validations
10
+
11
+ validates :uid, 'with_uid/uid' => true
12
+ end
13
+
14
+ ModelWithOptionalUid = Struct.new(:uid) do
15
+ include ActiveModel::Validations
16
+
17
+ validates :uid, 'with_uid/uid' => { allow_blank: true }
18
+ end
19
+
20
+ context 'model with required uid' do
21
+ subject(:model) { ModelWithRequiredUid.new }
22
+
23
+ it 'is invalid if uid is empty string' do
24
+ model.uid = ''
25
+
26
+ expect(model).to be_invalid
27
+ end
28
+
29
+ it 'is invalid if uid is nil' do
30
+ model.uid = nil
31
+
32
+ expect(model).to be_invalid
33
+ end
34
+
35
+ it 'is valid if uid is present' do
36
+ model.uid = '123'
37
+
38
+ expect(model).to be_valid
39
+ end
40
+
41
+ it 'is invalid if uid is present and contains forbidden chars' do
42
+ model.uid = ':/.123'
43
+
44
+ expect(model).to be_invalid
45
+ end
46
+ end
47
+
48
+ context 'model with optional uid' do
49
+ subject(:model) { ModelWithOptionalUid.new }
50
+
51
+ it 'is valid if uid is empty string' do
52
+ model.uid = ''
53
+
54
+ expect(model).to be_valid
55
+ end
56
+
57
+ it 'is valid if uid is nil' do
58
+ model.uid = nil
59
+
60
+ expect(model).to be_valid
61
+ end
62
+
63
+ it 'is valid if uid is present' do
64
+ model.uid = '123'
65
+
66
+ expect(model).to be_valid
67
+ end
68
+
69
+ it 'is invalid if uid is present and contains forbidden chars' do
70
+ model.uid = ':/.123'
71
+
72
+ expect(model).to be_invalid
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,50 @@
1
+ require 'spec_helper'
2
+ require 'support/model_with_uid'
3
+
4
+ RSpec.describe WithUid do
5
+ describe '.format' do
6
+ it do
7
+ formatted = WithUid.format('[The] unFormaTTEd, — String! & punctuations')
8
+ expect(formatted).to eq('the-unformatted-string-punctuations')
9
+ end
10
+ end
11
+
12
+ context 'generation' do
13
+ specify 'without block' do
14
+ model = ModelWithUid.new(name: 'b37')
15
+ expect do
16
+ model.valid?
17
+ end.to change {
18
+ model.uid
19
+ }.from(nil)
20
+ end
21
+
22
+ it 'success' do
23
+ model = ModelWithUid.new(name: 'b37')
24
+
25
+ model.generate_uid do
26
+ "#{name}-42"
27
+ end
28
+
29
+ expect(model.uid).to eq 'b37-42'
30
+ end
31
+
32
+ it 'set uid manual' do
33
+ model = ModelWithUid.new(uid: 'bbc', name: 'BBC')
34
+
35
+ model.generate_uid do
36
+ "#{name}-42"
37
+ end
38
+
39
+ expect(model.uid).to eq('bbc')
40
+ end
41
+
42
+ it 'run callbacks' do
43
+ model = ModelWithUid.new(uid: 'bbc', name: 'BBC')
44
+
45
+ expect(model).to receive(:generate_uid)
46
+
47
+ model.valid?
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,28 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'with_uid/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'with_uid'
8
+ spec.version = WithUid::VERSION
9
+ spec.authors = ['Tema Bolshakov', 'Others']
10
+ spec.email = ['abolshakov@spbtv.com']
11
+ spec.summary = 'Generate customizable uid for your ActiveRecord models'
12
+ spec.description = 'Generate customizable uid for your ActiveRecord models'
13
+ spec.homepage = 'https://github.com/SPBTV/with_uid'
14
+ spec.license = 'Apache License, Version 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 'activesupport', '>= 4'
22
+ spec.add_dependency 'activemodel', '>= 4'
23
+ spec.add_development_dependency 'activerecord', '~> 4.2'
24
+ spec.add_development_dependency 'sqlite3'
25
+ spec.add_development_dependency 'bundler', '~> 1.7'
26
+ spec.add_development_dependency 'rake', '~> 10.0'
27
+ spec.add_development_dependency 'rspec', '~> 3.2'
28
+ end
metadata ADDED
@@ -0,0 +1,166 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: with_uid
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.0.1
5
+ platform: ruby
6
+ authors:
7
+ - Tema Bolshakov
8
+ - Others
9
+ autorequire:
10
+ bindir: bin
11
+ cert_chain: []
12
+ date: 2015-03-13 00:00:00.000000000 Z
13
+ dependencies:
14
+ - !ruby/object:Gem::Dependency
15
+ name: activesupport
16
+ requirement: !ruby/object:Gem::Requirement
17
+ requirements:
18
+ - - ">="
19
+ - !ruby/object:Gem::Version
20
+ version: '4'
21
+ type: :runtime
22
+ prerelease: false
23
+ version_requirements: !ruby/object:Gem::Requirement
24
+ requirements:
25
+ - - ">="
26
+ - !ruby/object:Gem::Version
27
+ version: '4'
28
+ - !ruby/object:Gem::Dependency
29
+ name: activemodel
30
+ requirement: !ruby/object:Gem::Requirement
31
+ requirements:
32
+ - - ">="
33
+ - !ruby/object:Gem::Version
34
+ version: '4'
35
+ type: :runtime
36
+ prerelease: false
37
+ version_requirements: !ruby/object:Gem::Requirement
38
+ requirements:
39
+ - - ">="
40
+ - !ruby/object:Gem::Version
41
+ version: '4'
42
+ - !ruby/object:Gem::Dependency
43
+ name: activerecord
44
+ requirement: !ruby/object:Gem::Requirement
45
+ requirements:
46
+ - - "~>"
47
+ - !ruby/object:Gem::Version
48
+ version: '4.2'
49
+ type: :development
50
+ prerelease: false
51
+ version_requirements: !ruby/object:Gem::Requirement
52
+ requirements:
53
+ - - "~>"
54
+ - !ruby/object:Gem::Version
55
+ version: '4.2'
56
+ - !ruby/object:Gem::Dependency
57
+ name: sqlite3
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - ">="
61
+ - !ruby/object:Gem::Version
62
+ version: '0'
63
+ type: :development
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - ">="
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
70
+ - !ruby/object:Gem::Dependency
71
+ name: bundler
72
+ requirement: !ruby/object:Gem::Requirement
73
+ requirements:
74
+ - - "~>"
75
+ - !ruby/object:Gem::Version
76
+ version: '1.7'
77
+ type: :development
78
+ prerelease: false
79
+ version_requirements: !ruby/object:Gem::Requirement
80
+ requirements:
81
+ - - "~>"
82
+ - !ruby/object:Gem::Version
83
+ version: '1.7'
84
+ - !ruby/object:Gem::Dependency
85
+ name: rake
86
+ requirement: !ruby/object:Gem::Requirement
87
+ requirements:
88
+ - - "~>"
89
+ - !ruby/object:Gem::Version
90
+ version: '10.0'
91
+ type: :development
92
+ prerelease: false
93
+ version_requirements: !ruby/object:Gem::Requirement
94
+ requirements:
95
+ - - "~>"
96
+ - !ruby/object:Gem::Version
97
+ version: '10.0'
98
+ - !ruby/object:Gem::Dependency
99
+ name: rspec
100
+ requirement: !ruby/object:Gem::Requirement
101
+ requirements:
102
+ - - "~>"
103
+ - !ruby/object:Gem::Version
104
+ version: '3.2'
105
+ type: :development
106
+ prerelease: false
107
+ version_requirements: !ruby/object:Gem::Requirement
108
+ requirements:
109
+ - - "~>"
110
+ - !ruby/object:Gem::Version
111
+ version: '3.2'
112
+ description: Generate customizable uid for your ActiveRecord models
113
+ email:
114
+ - abolshakov@spbtv.com
115
+ executables: []
116
+ extensions: []
117
+ extra_rdoc_files: []
118
+ files:
119
+ - ".gitignore"
120
+ - ".rspec"
121
+ - ".travis.yml"
122
+ - Gemfile
123
+ - LICENSE
124
+ - README.md
125
+ - Rakefile
126
+ - lib/with_uid.rb
127
+ - lib/with_uid/uid_generator.rb
128
+ - lib/with_uid/uid_validator.rb
129
+ - lib/with_uid/version.rb
130
+ - spec/spec_helper.rb
131
+ - spec/support/model_with_uid.rb
132
+ - spec/with_uid/uid_generator_spec.rb
133
+ - spec/with_uid/uid_validator_spec.rb
134
+ - spec/with_uid_spec.rb
135
+ - with_uid.gemspec
136
+ homepage: https://github.com/SPBTV/with_uid
137
+ licenses:
138
+ - Apache License, Version 2.0
139
+ metadata: {}
140
+ post_install_message:
141
+ rdoc_options: []
142
+ require_paths:
143
+ - lib
144
+ required_ruby_version: !ruby/object:Gem::Requirement
145
+ requirements:
146
+ - - ">="
147
+ - !ruby/object:Gem::Version
148
+ version: '0'
149
+ required_rubygems_version: !ruby/object:Gem::Requirement
150
+ requirements:
151
+ - - ">="
152
+ - !ruby/object:Gem::Version
153
+ version: '0'
154
+ requirements: []
155
+ rubyforge_project:
156
+ rubygems_version: 2.4.5
157
+ signing_key:
158
+ specification_version: 4
159
+ summary: Generate customizable uid for your ActiveRecord models
160
+ test_files:
161
+ - spec/spec_helper.rb
162
+ - spec/support/model_with_uid.rb
163
+ - spec/with_uid/uid_generator_spec.rb
164
+ - spec/with_uid/uid_validator_spec.rb
165
+ - spec/with_uid_spec.rb
166
+ has_rdoc: