Module: Uuidable::ActiveRecord::ClassMethods

Includes:
Finder
Defined in:
lib/uuidable/active_record.rb

Overview

ClassMethods

Instance Method Summary collapse

Methods included from Finder

#find

Instance Method Details

#uuidable(as_param: true) ⇒ Object

rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity



24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/uuidable/active_record.rb', line 24

def uuidable(as_param: true) # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  # Configure all uuid columns for MySQL. Database may not be connected (i.e. on assets precompile), so we must supress errors.
  conn_config = respond_to?(:connection_db_config) ? connection_db_config.configuration_hash : connection_config

  if conn_config[:adapter].include?('mysql') && connection.data_source_exists?(table_name)
    begin
      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?
  end

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

  if as_param
    define_method :to_param do
      uuid
    end
  end

  define_method :uuid= do |val|
    raise UuidChangeError, 'Uuid changing is bad idea!' unless new_record? || uuid.blank? || uuid == val

    super(val)
  end
end