module HasChecksum::ClassMethods

Public Instance Methods

has_checksum(*config) click to toggle source
# File lib/has_checksum.rb, line 71
def has_checksum(*config)
  source, options = has_checksum_configure(config)

  if !options[:algorithm].respond_to?(:call)
    # TODO: use OpenSSL here too?
    begin
      options[:algorithm] = Digest.const_get(options[:algorithm].upcase)
    # Digest seems to only raise LoadError here but we add NameError for good measure
    rescue LoadError, NameError
      raise ArgumentError, "unknown algorithm '#{options[:algorithm]}'"
    end
  end

  options[:method] ||= "%s_checksum" % source.join("_")
  define_methods(:calculate_checksum, source, options)
end
has_signature(*config) click to toggle source
# File lib/has_checksum.rb, line 55
def has_signature(*config)
  source, options = has_checksum_configure(config)
  raise ArgumentError, "key option required to calculate a signature" unless options[:key]

  if !options[:algorithm].respond_to?(:call)
    begin
      options[:algorithm] = OpenSSL::Digest.new(options[:algorithm])
    rescue RuntimeError
      raise ArgumentError, "unknown algorithm '#{options[:algorithm]}'"
    end
  end

  options[:method] ||= "%s_signature" % source.join("_")
  define_methods(:calculate_signature, source, options)
end

Private Instance Methods

has_checksum_configure(config) click to toggle source
# File lib/has_checksum.rb, line 90
def has_checksum_configure(config)
  config.flatten!
  raise ArgumentError, "config required" if config.empty?

  options = config[-1].is_a?(Hash) ? config.pop : {}
  raise ArgumentError, "no column(s) specified" if config.empty?

  options[:algorithm] ||= "sha256"

  if self < ::ActiveRecord::Base
    extend ActiveRecord
  else
    extend PORO
  end

  [ Array(config), options ]
end