module HasChecksum::ActiveRecord

Private Instance Methods

define_methods(calculator, source, options) click to toggle source
# File lib/has_checksum.rb, line 125
def define_methods(calculator, source, options)
  klass = options[:algorithm]
  if klass.respond_to?(:call)
    define_method(options[:method]) { klass[digest_string(source)] }
  else
    define_method(options[:method]) { send(calculator, klass, digest_string(source), options) }
  end

  # Check if we a column to write to or if we only recalculate
  return unless columns_hash.include?(options[:method].to_s)

  watching = source.map(&:to_s)
  if options[:key].is_a?(Symbol)
    key = options[:key].to_s
    # if the key is a column it could change too and we must recalculate, e.g., updated_at
    watching += [key] if columns_hash.include?(key)
  end

  if klass.respond_to?(:call)
    after_create { update_column(options[:method], klass[digest_string(source)]) }
    around_update do |_, block|
      changed = (watching & changed_attributes.keys).any?
      block[]
      update_column(options[:method], klass[digest_string(source)]) if changed
    end
  else
    after_create { update_column(options[:method], public_send(options[:method])) }
    around_update do |_, block|
      changed = (watching & changed_attributes.keys).any?
      block[]
      update_column(options[:method], public_send(options[:method])) if changed
    end
  end
end