active_record_uniqueness_via_db 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA1:
3
+ metadata.gz: 9da850897aaec17bdb54551fd48fd915b1377562
4
+ data.tar.gz: df6e2d237f05b00e0d97071b209221fc85206678
5
+ SHA512:
6
+ metadata.gz: 4919adcbac7b4c0324a9b8223e3b3d7dd26d745d37915081882c7c3c77b9425c11bcee4c2e335af05459cc80ef176e68aed249da9f5d4b3ff24a70789e71c933
7
+ data.tar.gz: a50b43336b20b762bcdb2df7b6aede4d2b1b8699f4336e0d100f89b1d359eab6c2d95daaf8037916c536d2976a4a3f1146c55a8fc6a09d597a8367cc5c86ab62
data/.gitignore ADDED
@@ -0,0 +1,9 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /Gemfile.lock
4
+ /_yardoc/
5
+ /coverage/
6
+ /doc/
7
+ /pkg/
8
+ /spec/reports/
9
+ /tmp/
data/.rspec ADDED
@@ -0,0 +1,2 @@
1
+ --format documentation
2
+ --color
data/.travis.yml ADDED
@@ -0,0 +1,4 @@
1
+ language: ruby
2
+ rvm:
3
+ - 2.2.0
4
+ before_install: gem install bundler -v 1.10.6
@@ -0,0 +1,13 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
4
+
5
+ We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
6
+
7
+ Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct.
8
+
9
+ Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team.
10
+
11
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers.
12
+
13
+ This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.0.0, available at [http://contributor-covenant.org/version/1/0/0/](http://contributor-covenant.org/version/1/0/0/)
data/Gemfile ADDED
@@ -0,0 +1,4 @@
1
+ source 'https://rubygems.org'
2
+
3
+ # Specify your gem's dependencies in active_record_uniqueness_via_db.gemspec
4
+ gemspec
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2016 James Mac William
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,67 @@
1
+ [![Build
2
+ Status](https://travis-ci.org/jamesmacwilliam/active_record_uniqueness_via_db.svg?branch=master)](https://travis-ci.org/jamesmacwilliam/active_record_uniqueness_via_db)
3
+
4
+ [![Code
5
+ Climate](https://codeclimate.com/github/jamesmacwilliam/active_record_uniqueness_via_db/badges/gpa.svg)](https://codeclimate.com/github/jamesmacwilliam/active_record_uniqueness_via_db)
6
+
7
+ # ActiveRecordUniquenessViaDb
8
+
9
+ This simplifies validations by uniqueness using db constraints. Rails
10
+ uniqueness validations are not safe for concurrent processes, so we need
11
+ to add a db constraint anyway to ensure values are unique in the
12
+ database. This allows us to just rely on the error that constraint
13
+ raises rather than perform an extra select statement prior to
14
+ insert/updates
15
+
16
+ ```
17
+ validate :some_key, uniqueness: { via: :db }
18
+ ```
19
+
20
+ the rails uniqueness validation already accepts options rather than a
21
+ simple truthy value, this gem adds the `:via` key to those options
22
+
23
+ ## Installation
24
+
25
+ Add this line to your application's Gemfile:
26
+
27
+ ```ruby
28
+ gem 'active_record_uniqueness_via_db'
29
+ ```
30
+
31
+ And then execute:
32
+
33
+ $ bundle
34
+
35
+ Or install it yourself as:
36
+
37
+ $ gem install active_record_uniqueness_via_db
38
+
39
+ run this command to set up the initializer:
40
+
41
+ ```ruby
42
+ rails generate active_record_uniqueness_via_db:install
43
+ ```
44
+
45
+ ## Usage
46
+
47
+ ```
48
+ validate :some_key, uniqueness: { via: :db }
49
+ ```
50
+
51
+ ## Development
52
+
53
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
54
+
55
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
56
+
57
+ Note: to add databases, add a file under `lib/adapters/db_adapter_name.rb`
58
+ that implements the `error_matches_att` method
59
+ ## Contributing
60
+
61
+ Bug reports and pull requests are welcome on GitHub at https://github.com/[USERNAME]/active_record_uniqueness_via_db. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](contributor-covenant.org) code of conduct.
62
+
63
+
64
+ ## License
65
+
66
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
67
+
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
@@ -0,0 +1,25 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'active_record_uniqueness_via_db/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = "active_record_uniqueness_via_db"
8
+ spec.version = ActiveRecordUniquenessViaDb::VERSION
9
+ spec.authors = ["James Mac William"]
10
+ spec.email = ["jimmy.macwilliam@gmail.com"]
11
+
12
+ spec.summary = %q{Extend ActiveRecord uniqueness validations with via: :db option.}
13
+ spec.homepage = "https://github.com/jamesmacwilliam/active_record_uniqueness_via_db"
14
+ spec.license = "MIT"
15
+
16
+ spec.files = `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
17
+ spec.bindir = "exe"
18
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
19
+ spec.require_paths = ["lib"]
20
+
21
+ spec.add_development_dependency "bundler", "~> 1.10"
22
+ spec.add_development_dependency "rake", "~> 10.0"
23
+ spec.add_dependency "railties", ">= 4.1.0", "< 5.1"
24
+ spec.add_development_dependency "rspec"
25
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "active_record_uniqueness_via_db"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start
data/bin/setup ADDED
@@ -0,0 +1,7 @@
1
+ #!/bin/bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+
5
+ bundle install
6
+
7
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,30 @@
1
+ module ActiveRecord
2
+ module Validations
3
+ class UniquenessValidator < ActiveModel::EachValidator
4
+
5
+ alias :old_validate_each :validate_each
6
+ alias :old_initialize :initialize
7
+
8
+ def initialize(options)
9
+ if options[:via].present? && !(options[:via] == :db)
10
+ raise ArgumentError, "the :via option only accepts :db"
11
+ end
12
+ old_initialize(options)
13
+ end
14
+
15
+ def validate_each(record, attribute, value)
16
+ error_options =
17
+ options.
18
+ merge(:value => value).
19
+ except(:case_sensitive, :scope, :conditions)
20
+
21
+ ActiveRecordUniquenessViaDb::Builder.call(
22
+ record,
23
+ attribute,
24
+ !options[:via],
25
+ error_options,
26
+ ) { old_validate_each(record, attribute, value) }
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,8 @@
1
+ require 'active_record_uniqueness_via_db/adapters/mysql2'
2
+ require 'active_support/inflector'
3
+
4
+ class ActiveRecordUniquenessViaDb::Adapter
5
+ def self.for(ar_adapter)
6
+ "ActiveRecordUniquenessViaDb::Adapters::#{ar_adapter.classify}".constantize.new
7
+ end
8
+ end
@@ -0,0 +1,5 @@
1
+ class ActiveRecordUniquenessViaDb::Adapters::Mysql2
2
+ def error_matches_attr(attr, err_msg)
3
+ err_msg =~ /Mysql2[:]*Error.*Duplicate entry.*for key ['][a-z0-9_]*#{attr}[']/
4
+ end
5
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveRecordUniquenessViaDb::Adapters
2
+
3
+ end
@@ -0,0 +1,37 @@
1
+ class ActiveRecordUniquenessViaDb::Builder
2
+ attr_accessor :block, :record, :attr_name, :always_block, :attrs_to_rescue,
3
+ :error_options
4
+
5
+ def initialize(record, attr_name, always_block, error_options, &block)
6
+ @record = record
7
+ @block = block
8
+ @attr_name = attr_name
9
+ @always_block = always_block
10
+ @error_options = error_options
11
+ @attrs_to_rescue = record.
12
+ instance_variable_get("@#{ActiveRecordUniquenessViaDb::ATTRS_IVAR}") || {}
13
+ @attrs_to_rescue.delete(attr_name)
14
+ end
15
+
16
+ def call
17
+ via_db? ? @attrs_to_rescue[attr_name] = error_options : block.call
18
+ specify_attributes_to_rescue_db_error
19
+ end
20
+
21
+ def self.call(record, attr_name, always_block, error_options, &block)
22
+ new(record, attr_name, always_block, error_options, &block).call
23
+ end
24
+
25
+ private
26
+
27
+ def specify_attributes_to_rescue_db_error
28
+ record.instance_variable_set(
29
+ "@#{ActiveRecordUniquenessViaDb::ATTRS_IVAR}",
30
+ attrs_to_rescue
31
+ )
32
+ end
33
+
34
+ def via_db?
35
+ record.changed? && !always_block
36
+ end
37
+ end
@@ -0,0 +1,31 @@
1
+ class ActiveRecordUniquenessViaDb::Validator
2
+ attr_accessor :adapter, :record, :exception, :attrs_to_rescue
3
+
4
+ def initialize(adapter, record, exception)
5
+ @adapter = adapter
6
+ @record = record
7
+ @exception = exception
8
+ @attrs_to_rescue = record.
9
+ instance_variable_get("@#{ActiveRecordUniquenessViaDb::ATTRS_IVAR}") || {}
10
+ end
11
+
12
+ def call
13
+ if attribute_with_error
14
+ record.errors.add(attribute_with_error.first, :taken, attribute_with_error.last)
15
+ else
16
+ raise exception
17
+ end
18
+ end
19
+
20
+ def self.validate(adapter, record, exception)
21
+ new(adapter,record, exception).call
22
+ end
23
+
24
+ private
25
+
26
+ def attribute_with_error
27
+ @attr_with_error ||=
28
+ attrs_to_rescue.
29
+ find { |attr, _| adapter.error_matches_attr(attr, exception.message) }
30
+ end
31
+ end
@@ -0,0 +1,3 @@
1
+ module ActiveRecordUniquenessViaDb
2
+ VERSION = "0.1.0"
3
+ end
@@ -0,0 +1,11 @@
1
+ require 'active_record'
2
+ require 'active_record_uniqueness_via_db/version'
3
+ require 'active_record_uniqueness_via_db/builder'
4
+ require 'active_record_uniqueness_via_db/validator'
5
+ require 'active_record_uniqueness_via_db/adapters'
6
+ require 'active_record_uniqueness_via_db/adapter'
7
+ require 'active_record/validations/uniqueness_validator'
8
+
9
+ module ActiveRecordUniquenessViaDb
10
+ ATTRS_IVAR = :attrs_to_rescue_uniqueness_db
11
+ end
@@ -0,0 +1,14 @@
1
+ require 'rails/generators/base'
2
+
3
+ module ActiveRecordUniquenessViaDb
4
+ module Generators
5
+ class InstallGenerator < Rails::Generators::Base
6
+ source_root File.expand_path("../../templates", __FILE__)
7
+ desc "Creates an ActiveRecordUniqunessViaDb initializer."
8
+
9
+ def copy_initializer
10
+ template "active_record_uniqueness_via_db.rb", "config/initializers/active_record_uniqueness_via_db.rb"
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,36 @@
1
+ module ActiveRecord
2
+ module Persistence
3
+ extend ActiveSupport::Concern
4
+
5
+ cattr_accessor ActiveRecordUniquenessViaDb::ATTRS_IVAR
6
+
7
+ alias :original_create_or_update :create_or_update
8
+ alias :original_save! :save!
9
+
10
+ def create_or_update
11
+ original_create_or_update
12
+ rescue ActiveRecord::RecordNotUnique => e
13
+ uniqueness_via_db_validator(e)
14
+ @original_validation_error =
15
+ ActiveRecord::RecordNotUnique.new(self.errors.full_messages.first)
16
+ false
17
+ end
18
+
19
+ def save!(*)
20
+ original_save!
21
+ rescue ActiveRecord::RecordNotSaved => e
22
+ raise(@original_validation_error) if @original_validation_error
23
+ raise e
24
+ end
25
+
26
+ private
27
+
28
+ def uniqueness_via_db_validator(exception)
29
+ ActiveRecordUniquenessViaDb::Validator.validate(
30
+ ActiveRecordUniquenessViaDb::Adapter.for(self.class.connection_config[:adapter]),
31
+ self,
32
+ exception
33
+ )
34
+ end
35
+ end
36
+ end
metadata ADDED
@@ -0,0 +1,128 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: active_record_uniqueness_via_db
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - James Mac William
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2016-04-05 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: bundler
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - "~>"
18
+ - !ruby/object:Gem::Version
19
+ version: '1.10'
20
+ type: :development
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - "~>"
25
+ - !ruby/object:Gem::Version
26
+ version: '1.10'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rake
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '10.0'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '10.0'
41
+ - !ruby/object:Gem::Dependency
42
+ name: railties
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - ">="
46
+ - !ruby/object:Gem::Version
47
+ version: 4.1.0
48
+ - - "<"
49
+ - !ruby/object:Gem::Version
50
+ version: '5.1'
51
+ type: :runtime
52
+ prerelease: false
53
+ version_requirements: !ruby/object:Gem::Requirement
54
+ requirements:
55
+ - - ">="
56
+ - !ruby/object:Gem::Version
57
+ version: 4.1.0
58
+ - - "<"
59
+ - !ruby/object:Gem::Version
60
+ version: '5.1'
61
+ - !ruby/object:Gem::Dependency
62
+ name: rspec
63
+ requirement: !ruby/object:Gem::Requirement
64
+ requirements:
65
+ - - ">="
66
+ - !ruby/object:Gem::Version
67
+ version: '0'
68
+ type: :development
69
+ prerelease: false
70
+ version_requirements: !ruby/object:Gem::Requirement
71
+ requirements:
72
+ - - ">="
73
+ - !ruby/object:Gem::Version
74
+ version: '0'
75
+ description:
76
+ email:
77
+ - jimmy.macwilliam@gmail.com
78
+ executables: []
79
+ extensions: []
80
+ extra_rdoc_files: []
81
+ files:
82
+ - ".gitignore"
83
+ - ".rspec"
84
+ - ".travis.yml"
85
+ - CODE_OF_CONDUCT.md
86
+ - Gemfile
87
+ - LICENSE.txt
88
+ - README.md
89
+ - Rakefile
90
+ - active_record_uniqueness_via_db.gemspec
91
+ - bin/console
92
+ - bin/setup
93
+ - lib/active_record/validations/uniqueness_validator.rb
94
+ - lib/active_record_uniqueness_via_db.rb
95
+ - lib/active_record_uniqueness_via_db/adapter.rb
96
+ - lib/active_record_uniqueness_via_db/adapters.rb
97
+ - lib/active_record_uniqueness_via_db/adapters/mysql2.rb
98
+ - lib/active_record_uniqueness_via_db/builder.rb
99
+ - lib/active_record_uniqueness_via_db/validator.rb
100
+ - lib/active_record_uniqueness_via_db/version.rb
101
+ - lib/generators/active_record_uniqueness_via_db/install_generator.rb
102
+ - lib/generators/templates/active_record_uniqueness_via_db.rb
103
+ homepage: https://github.com/jamesmacwilliam/active_record_uniqueness_via_db
104
+ licenses:
105
+ - MIT
106
+ metadata: {}
107
+ post_install_message:
108
+ rdoc_options: []
109
+ require_paths:
110
+ - lib
111
+ required_ruby_version: !ruby/object:Gem::Requirement
112
+ requirements:
113
+ - - ">="
114
+ - !ruby/object:Gem::Version
115
+ version: '0'
116
+ required_rubygems_version: !ruby/object:Gem::Requirement
117
+ requirements:
118
+ - - ">="
119
+ - !ruby/object:Gem::Version
120
+ version: '0'
121
+ requirements: []
122
+ rubyforge_project:
123
+ rubygems_version: 2.4.5
124
+ signing_key:
125
+ specification_version: 4
126
+ summary: 'Extend ActiveRecord uniqueness validations with via: :db option.'
127
+ test_files: []
128
+ has_rdoc: