Skip to content

Commit

Permalink
Better transition period handling (#18)
Browse files Browse the repository at this point in the history
  • Loading branch information
gsmetal committed Jun 13, 2024
1 parent 9fa3950 commit 615ebd2
Show file tree
Hide file tree
Showing 5 changed files with 25 additions and 4 deletions.
2 changes: 1 addition & 1 deletion Gemfile.lock
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
uuidable (1.0.2)
uuidable (1.0.3)
activerecord (>= 4.2, < 7.2)
mysql-binuuid-rails (>= 1.3, < 2)
uuidtools (>= 2.1, < 3)
Expand Down
1 change: 1 addition & 0 deletions lib/uuidable.rb
Original file line number Diff line number Diff line change
Expand Up @@ -17,4 +17,5 @@ def generate_uuid

require 'uuidable/migration'
require 'uuidable/v1_migration_helpers'
require 'uuidable/v1_model_migration'
require 'uuidable/active_record'
5 changes: 3 additions & 2 deletions lib/uuidable/active_record.rb
Original file line number Diff line number Diff line change
Expand Up @@ -30,16 +30,17 @@ def uuidable(as_param: true) # rubocop:disable Metrics/AbcSize, Metrics/Cyclomat
columns.select { |c| c.type == :binary && c.limit == 16 && c.name.include?('uuid') }.each do |column|
attribute column.name.to_sym, MySQLBinUUID::Type.new
end

include V1ModelMigration if columns.any? { |c| c.name.include?(V1MigrationHelpers::OLD_POSTFIX) }
rescue ::ActiveRecord::ConnectionNotEstablished, Mysql2::Error::ConnectionError, ::ActiveRecord::NoDatabaseError # rubocop:disable Lint/SuppressedException
end
end

after_initialize do
self.uuid = Uuidable.generate_uuid if attributes.keys.include?('uuid') && uuid.blank?
self.uuid__old = uuid if respond_to?(:uuid__old)
end

validates :uuid, presence: true, uniqueness: true, if: :uuid_changed?
validates :uuid, presence: true, uniqueness: true, if: -> { try :uuid_changed? }

if as_param
define_method :to_param do
Expand Down
19 changes: 19 additions & 0 deletions lib/uuidable/v1_model_migration.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
# frozen_string_literal: true

module Uuidable
# Temporary helpers for transition period when migrating to v1
module V1ModelMigration
extend ActiveSupport::Concern

included do
before_validation do
attributes.each_key do |attr_name|
next unless attr_name.include?(V1MigrationHelpers::OLD_POSTFIX)

new_attr_name = attr_name.gsub(V1MigrationHelpers::OLD_POSTFIX, '')
public_send("#{attr_name}=", attributes[new_attr_name].to_s)
end
end
end
end
end
2 changes: 1 addition & 1 deletion lib/uuidable/version.rb
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
# frozen_string_literal: true

module Uuidable
VERSION = '1.0.2'
VERSION = '1.0.3'
end

0 comments on commit 615ebd2

Please sign in to comment.