adaptive_alias 0.0.1

Sign up to get free protection for your applications and to get access to all the features.
data/CHANGELOG.md ADDED
@@ -0,0 +1 @@
1
+ ## Change Log
@@ -0,0 +1,49 @@
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, and in the interest of
4
+ fostering an open and welcoming community, we pledge to respect all people who
5
+ contribute through reporting issues, posting feature requests, updating
6
+ documentation, submitting pull requests or patches, and other activities.
7
+
8
+ We are committed to making participation in this project a harassment-free
9
+ experience for everyone, regardless of level of experience, gender, gender
10
+ identity and expression, sexual orientation, disability, personal appearance,
11
+ body size, race, ethnicity, age, religion, or nationality.
12
+
13
+ Examples of unacceptable behavior by participants include:
14
+
15
+ * The use of sexualized language or imagery
16
+ * Personal attacks
17
+ * Trolling or insulting/derogatory comments
18
+ * Public or private harassment
19
+ * Publishing other's private information, such as physical or electronic
20
+ addresses, without explicit permission
21
+ * Other unethical or unprofessional conduct
22
+
23
+ Project maintainers have the right and responsibility to remove, edit, or
24
+ reject comments, commits, code, wiki edits, issues, and other contributions
25
+ that are not aligned to this Code of Conduct, or to ban temporarily or
26
+ permanently any contributor for other behaviors that they deem inappropriate,
27
+ threatening, offensive, or harmful.
28
+
29
+ By adopting this Code of Conduct, project maintainers commit themselves to
30
+ fairly and consistently applying these principles to every aspect of managing
31
+ this project. Project maintainers who do not follow or enforce the Code of
32
+ Conduct may be permanently removed from the project team.
33
+
34
+ This code of conduct applies both within project spaces and in public spaces
35
+ when an individual is representing the project or its community.
36
+
37
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
38
+ reported by contacting a project maintainer at mrtmrt15xn@yahoo.com.tw. All
39
+ complaints will be reviewed and investigated and will result in a response that
40
+ is deemed necessary and appropriate to the circumstances. Maintainers are
41
+ obligated to maintain confidentiality with regard to the reporter of an
42
+ incident.
43
+
44
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage],
45
+ version 1.3.0, available at
46
+ [http://contributor-covenant.org/version/1/3/0/][version]
47
+
48
+ [homepage]: http://contributor-covenant.org
49
+ [version]: http://contributor-covenant.org/version/1/3/0/
data/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2020 Rumble Huang
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 all
13
+ 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 THE
21
+ SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,46 @@
1
+ # adaptive_alias
2
+
3
+ [![Gem Version](https://img.shields.io/gem/v/adaptive_alias.svg?style=flat)](http://rubygems.org/gems/adaptive_alias)
4
+ [![Build Status](https://github.com/khiav223577/adaptive_alias/workflows/Ruby/badge.svg)](https://github.com/khiav223577/adaptive_alias/actions)
5
+ [![RubyGems](http://img.shields.io/gem/dt/adaptive_alias.svg?style=flat)](http://rubygems.org/gems/adaptive_alias)
6
+ [![Code Climate](https://codeclimate.com/github/khiav223577/adaptive_alias/badges/gpa.svg)](https://codeclimate.com/github/khiav223577/adaptive_alias)
7
+ [![Test Coverage](https://codeclimate.com/github/khiav223577/adaptive_alias/badges/coverage.svg)](https://codeclimate.com/github/khiav223577/adaptive_alias/coverage)
8
+
9
+ Extend attribute_alias and make it be adaptive with realtime database schema.
10
+
11
+ ## Supports
12
+ - Ruby 2.6 ~ 2.7, 3.0 ~ 3.1
13
+ - Rails 6.0, 6.1, 7.0
14
+
15
+ ## Installation
16
+
17
+ ```ruby
18
+ gem 'adaptive_alias'
19
+ ```
20
+
21
+ And then execute:
22
+
23
+ $ bundle
24
+
25
+ Or install it yourself as:
26
+
27
+ $ gem install adaptive_alias
28
+
29
+ ## Usage
30
+
31
+
32
+ ## Development
33
+
34
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake test` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
35
+
36
+ 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).
37
+
38
+ ## Contributing
39
+
40
+ Bug reports and pull requests are welcome on GitHub at https://github.com/khiav223577/adaptive_alias. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to the [Contributor Covenant](http://contributor-covenant.org) code of conduct.
41
+
42
+
43
+ ## License
44
+
45
+ The gem is available as open source under the terms of the [MIT License](http://opensource.org/licenses/MIT).
46
+
data/Rakefile ADDED
@@ -0,0 +1,10 @@
1
+ require 'bundler/gem_tasks'
2
+ require 'rake/testtask'
3
+
4
+ Rake::TestTask.new(:test) do |t|
5
+ t.libs << 'test'
6
+ t.libs << 'lib'
7
+ t.test_files = FileList['test/**/*_test.rb']
8
+ end
9
+
10
+ task default: :test
@@ -0,0 +1,45 @@
1
+ # coding: utf-8
2
+ lib = File.expand_path('../lib', __FILE__)
3
+ $LOAD_PATH.unshift(lib) unless $LOAD_PATH.include?(lib)
4
+ require 'adaptive_alias/version'
5
+
6
+ Gem::Specification.new do |spec|
7
+ spec.name = 'adaptive_alias'
8
+ spec.version = AdaptiveAlias::VERSION
9
+ spec.authors = ['khiav reoy']
10
+ spec.email = ['mrtmrt15xn@yahoo.com.tw']
11
+
12
+ spec.summary = 'Extend attribute_alias and make it be adaptive with realtime database schema'
13
+ spec.description = 'Extend attribute_alias and make it be adaptive with realtime database schema'
14
+ spec.homepage = 'https://github.com/khiav223577/adaptive_alias'
15
+ spec.license = 'MIT'
16
+
17
+ # Prevent pushing this gem to RubyGems.org by setting 'allowed_push_host', or
18
+ # delete this section to allow pushing this gem to any host.
19
+ # if spec.respond_to?(:metadata)
20
+ # spec.metadata['allowed_push_host'] = "TODO: Set to 'http://mygemserver.com'"
21
+ # else
22
+ # raise "RubyGems 2.0 or newer is required to protect against public gem pushes."
23
+ # end
24
+
25
+ spec.files = `git ls-files -z`.split("\x0").reject{|f| f.match(%r{^(test|spec|features)/}) }
26
+ spec.bindir = 'exe'
27
+ spec.executables = spec.files.grep(%r{^exe/}){|f| File.basename(f) }
28
+ spec.require_paths = ['lib']
29
+ spec.metadata = {
30
+ 'homepage_uri' => 'https://github.com/khiav223577/adaptive_alias',
31
+ 'changelog_uri' => 'https://github.com/khiav223577/adaptive_alias/blob/master/CHANGELOG.md',
32
+ 'source_code_uri' => 'https://github.com/khiav223577/adaptive_alias',
33
+ 'documentation_uri' => 'https://www.rubydoc.info/gems/adaptive_alias',
34
+ 'bug_tracker_uri' => 'https://github.com/khiav223577/adaptive_alias/issues',
35
+ }
36
+
37
+ spec.add_development_dependency 'bundler', '>= 1.17', '< 3.x'
38
+ spec.add_development_dependency 'rake', '~> 12.0'
39
+ spec.add_development_dependency 'sqlite3', '~> 1.3'
40
+ spec.add_development_dependency 'minitest', '~> 5.0'
41
+ spec.add_development_dependency 'backports', '~> 3.15.0'
42
+
43
+ spec.add_dependency 'activerecord', '>= 3'
44
+ spec.add_dependency 'rails_compatibility', '>= 0.0.8'
45
+ end
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require 'bundler/setup'
4
+ require 'adaptive_alias'
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,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install --gemfile=gemfiles/4.2.gemfile
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,10 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'activerecord', '~> 6.0.0'
4
+
5
+ group :test do
6
+ gem 'simplecov', '< 0.18'
7
+ gem 'mysql2', '0.5.3'
8
+ end
9
+
10
+ gemspec path: '../'
@@ -0,0 +1,10 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'activerecord', '~> 6.1.3'
4
+
5
+ group :test do
6
+ gem 'simplecov', '< 0.18'
7
+ gem 'mysql2', '0.5.3'
8
+ end
9
+
10
+ gemspec path: '../'
@@ -0,0 +1,11 @@
1
+ source 'https://rubygems.org'
2
+
3
+ gem 'zeitwerk'
4
+ gem 'activerecord', '~> 7.0.0'
5
+
6
+ group :test do
7
+ gem 'simplecov', '< 0.18'
8
+ gem 'mysql2', '0.5.3'
9
+ end
10
+
11
+ gemspec path: '../'
@@ -0,0 +1,20 @@
1
+ require 'active_record'
2
+
3
+ module ActiveRecord::AttributeMethods::Read
4
+ def read_attribute(attr_name, &block) # :nodoc:
5
+ name = attr_name.to_s
6
+ name = self.class.attribute_aliases[name] || name
7
+
8
+ name = @primary_key if name == 'id' && @primary_key
9
+ _read_attribute(name, &block)
10
+ end
11
+
12
+ def _read_attribute(attr_name, &block) # :nodoc:
13
+ name = attr_name.to_s
14
+ name = self.class.attribute_aliases[name] || name
15
+
16
+ sync_with_transaction_state if @transaction_state&.finalized?
17
+ return yield if block_given? && !@attributes.key?(name)
18
+ @attributes.fetch_value(name, &block)
19
+ end
20
+ end
@@ -0,0 +1,27 @@
1
+ require 'active_model'
2
+
3
+ module ActiveModel::AttributeMethods
4
+ module ClassMethods
5
+ def remove_proxy_call(mod, name)
6
+ defn = if NAME_COMPILABLE_REGEXP.match?(name)
7
+ "undef #{name}"
8
+ else
9
+ "remove_method(:'#{name}')"
10
+ end
11
+
12
+ mod.module_eval defn, __FILE__, __LINE__ + 1
13
+ end
14
+
15
+ def remove_alias_attribute(new_name)
16
+ # association_scope -> add_constraints -> last_chain_scope -> where!(key => model[foreign_key])
17
+ # self[attr_name] -> read_attribute(attr_name) -> attribute_aliases
18
+ # where! -> where_clause_factory.build -> attributes = predicate_builder.resolve_column_aliases(opts) -> attribute_aliases
19
+ self.attribute_aliases = attribute_aliases.except(new_name.to_s)
20
+
21
+ attribute_method_matchers.each do |matcher|
22
+ matcher_new = matcher.method_name(new_name).to_s
23
+ remove_proxy_call self, matcher_new
24
+ end
25
+ end
26
+ end
27
+ end
@@ -0,0 +1,13 @@
1
+ module AdaptiveAlias
2
+ module Hooks
3
+ module Association
4
+ def find_target(*)
5
+ AdaptiveAlias.rescue_statement_invalid(nil){ super }
6
+ end
7
+ end
8
+ end
9
+ end
10
+
11
+ class ActiveRecord::Associations::Association
12
+ prepend AdaptiveAlias::Hooks::Association
13
+ end
@@ -0,0 +1,13 @@
1
+ module AdaptiveAlias
2
+ module Hooks
3
+ module AssociationScope
4
+ def last_chain_scope(*)
5
+ AdaptiveAlias.rescue_missing_attribute{ super }
6
+ end
7
+ end
8
+ end
9
+ end
10
+
11
+ class ActiveRecord::Associations::AssociationScope
12
+ prepend AdaptiveAlias::Hooks::AssociationScope
13
+ end
@@ -0,0 +1,21 @@
1
+ module AdaptiveAlias
2
+ module Hooks
3
+ module Relation
4
+ def pluck(*)
5
+ AdaptiveAlias.rescue_statement_invalid(self){ super }
6
+ end
7
+
8
+ def select_all(*)
9
+ AdaptiveAlias.rescue_statement_invalid(self){ super }
10
+ end
11
+
12
+ def exec_queries(*)
13
+ AdaptiveAlias.rescue_statement_invalid(self){ super }
14
+ end
15
+ end
16
+ end
17
+ end
18
+
19
+ class ActiveRecord::Relation
20
+ prepend AdaptiveAlias::Hooks::Relation
21
+ end
@@ -0,0 +1,13 @@
1
+ module AdaptiveAlias
2
+ module Hooks
3
+ module SingularAssociation
4
+ def reader(*)
5
+ AdaptiveAlias.rescue_missing_attribute{ super }
6
+ end
7
+ end
8
+ end
9
+ end
10
+
11
+ class ActiveRecord::Associations::SingularAssociation
12
+ prepend AdaptiveAlias::Hooks::SingularAssociation
13
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'adaptive_alias/patches/base'
4
+
5
+ module AdaptiveAlias
6
+ module Patches
7
+ class BackPatch < Base
8
+ def apply!
9
+ AdaptiveAlias.current_patches[[@klass, @old_column, @new_column]] = self
10
+ @klass.alias_attribute(@old_column, @new_column)
11
+ add_hooks!(current_column: @new_column, alias_column: @old_column, log_warning: true)
12
+ end
13
+
14
+ def remove!
15
+ super
16
+ @klass.remove_alias_attribute(@old_column)
17
+ ForwardPatch.new(@klass, @old_column, @new_column).apply!
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,75 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AdaptiveAlias
4
+ module Patches
5
+ class Base
6
+ attr_reader :fix_association
7
+ attr_reader :fix_missing_attribute
8
+ attr_reader :removed
9
+
10
+ def initialize(klass, old_column, new_column)
11
+ @klass = klass
12
+ @old_column = old_column
13
+ @new_column = new_column
14
+ end
15
+
16
+ def add_hooks!(current_column:, alias_column:, log_warning: false)
17
+ patch = self
18
+ old_column = @old_column
19
+ new_column = @new_column
20
+
21
+ AdaptiveAlias.get_or_create_model_module(@klass).instance_exec do
22
+ remove_method(new_column) if method_defined?(new_column)
23
+ define_method(new_column) do
24
+ AdaptiveAlias.rescue_missing_attribute{ self[new_column] }
25
+ end
26
+
27
+ remove_method(old_column) if method_defined?(old_column)
28
+ define_method(old_column) do
29
+ patch.log_warning if log_warning
30
+ AdaptiveAlias.rescue_missing_attribute{ self[old_column] }
31
+ end
32
+ end
33
+
34
+ expected_error_message = "Mysql2::Error: Unknown column '#{@klass.table_name}.#{current_column}' in 'where clause'".freeze
35
+
36
+ @fix_missing_attribute = proc do
37
+ next false if patch.removed
38
+
39
+ patch.remove!
40
+ next true
41
+ end
42
+
43
+ @fix_association = proc do |target, error|
44
+ next false if patch.removed || error.message != expected_error_message
45
+
46
+ patch.remove!
47
+
48
+ if target
49
+ hash = target.where_values_hash
50
+ hash[alias_column] = hash.delete(current_column) if hash.key?(current_column)
51
+ target.instance_variable_set(:@arel, nil)
52
+ target.unscope!(:where).where!(hash)
53
+ end
54
+
55
+ next true
56
+ end
57
+ end
58
+
59
+ def log_warning
60
+ if @prev_warning_time == nil || @prev_warning_time < AdaptiveAlias.log_interval.ago
61
+ @prev_warning_time = Time.now
62
+ AdaptiveAlias.unexpected_old_column_proc&.call
63
+ end
64
+ end
65
+
66
+ def remove!
67
+ @removed = true
68
+ @klass.send(:reload_schema_from_cache)
69
+ @klass.initialize_find_by_cache
70
+ @fix_association = nil
71
+ @fix_missing_attribute = nil
72
+ end
73
+ end
74
+ end
75
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'adaptive_alias/patches/base'
4
+
5
+ module AdaptiveAlias
6
+ module Patches
7
+ class ForwardPatch < Base
8
+ def apply!
9
+ AdaptiveAlias.current_patches[[@klass, @old_column, @new_column]] = self
10
+ @klass.alias_attribute(@new_column, @old_column)
11
+ add_hooks!(current_column: @old_column, alias_column: @new_column)
12
+ end
13
+
14
+ def remove!
15
+ super
16
+ @klass.remove_alias_attribute(@new_column)
17
+ BackPatch.new(@klass, @old_column, @new_column).apply!
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,3 @@
1
+ module AdaptiveAlias
2
+ VERSION = '0.0.1'
3
+ end
@@ -0,0 +1,65 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'adaptive_alias/version'
4
+ require 'adaptive_alias/active_model_patches/read_attribute'
5
+ require 'adaptive_alias/active_model_patches/remove_alias_attribute'
6
+ require 'adaptive_alias/patches/back_patch'
7
+ require 'adaptive_alias/patches/forward_patch'
8
+
9
+ require 'adaptive_alias/hooks/association'
10
+ require 'adaptive_alias/hooks/association_scope'
11
+ require 'adaptive_alias/hooks/singular_association'
12
+ require 'adaptive_alias/hooks/relation'
13
+
14
+ module AdaptiveAlias
15
+ @log_interval = 10 * 60
16
+ @current_patches = {}
17
+ @model_modules ||= {}
18
+
19
+ class << self
20
+ attr_accessor :unexpected_old_column_proc
21
+ attr_accessor :log_interval
22
+ attr_accessor :current_patches
23
+ end
24
+
25
+ class << self
26
+ def [](old_column, new_column)
27
+ old_column = old_column.to_sym
28
+ new_column = new_column.to_sym
29
+
30
+ Module.new do
31
+ extend ActiveSupport::Concern
32
+
33
+ included do
34
+ if column_names.include?(new_column)
35
+ Patches::BackPatch.new(self, old_column, new_column).apply!
36
+ else
37
+ Patches::ForwardPatch.new(self, old_column, new_column).apply!
38
+ end
39
+ end
40
+ end
41
+ end
42
+
43
+ def rescue_statement_invalid(relation)
44
+ yield
45
+ rescue ActiveRecord::StatementInvalid => error
46
+ raise error if AdaptiveAlias.current_patches.all?{|_key, patch| !patch.fix_association.call(relation, error) }
47
+ retry
48
+ end
49
+
50
+ def rescue_missing_attribute
51
+ yield
52
+ rescue ActiveModel::MissingAttributeError => error
53
+ raise error if AdaptiveAlias.current_patches.all?{|_key, patch| !patch.fix_missing_attribute.call }
54
+ retry
55
+ end
56
+
57
+ def get_or_create_model_module(klass)
58
+ return @model_modules[klass] if @model_modules[klass]
59
+
60
+ @model_modules[klass] = Module.new
61
+ klass.prepend(@model_modules[klass])
62
+ return @model_modules[klass]
63
+ end
64
+ end
65
+ end