Class: BatchKit::Database::MD5

Inherits:
Object
  • Object
show all
Defined in:
lib/batch-kit/database/models.rb

Overview

Records an MD5 hash of String objects, which are used to detect when items such as jobs have changed. This in turn is used to increment a version number on objects.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(obj_type, obj_name, string, digest = nil) ⇒ MD5

Create a new MD5 hash of an object



59
60
61
62
63
64
65
66
67
# File 'lib/batch-kit/database/models.rb', line 59

def initialize(obj_type, obj_name, string, digest = nil)
    obj_ver = self.class.where(Sequel.function(:upper, :object_name) => obj_name.upcase,
                               Sequel.function(:upper, :object_type) => obj_type.upcase).
                         max(:object_version) || 0
    super(object_type: obj_type, object_name: obj_name,
          object_version: obj_ver + 1,
          md5_digest: digest || Digest::MD5.hexdigest(string),
          md5_created_at: model.dataset.current_datetime)
end

Class Method Details

.check(obj_type, obj_name, string) ⇒ Boolean, String

Checks to see if the recorded MD5 digest of string matches the MD5 digest of string as calculated by Digest::MD5.

Returns:

  • (Boolean, String)

    Returns two values in an array: a boolean indicating whether the digest value is the same, and the actual calculated value for the MD5 digest of string.



46
47
48
49
50
51
52
53
54
55
# File 'lib/batch-kit/database/models.rb', line 46

def self.check(obj_type, obj_name, string)
    digest = Digest::MD5.hexdigest(string)
    # Attempt to retrieve the MD5 for the schema; could fail if not deployed
    md5 = self.for(obj_name, obj_type, digest) rescue nil
    if md5
        [md5.md5_id, md5]
    else
        [nil, self.new(obj_type, obj_name, string, digest)]
    end
end

.check_schema(schema) ⇒ Object

Checks that the BatchKit database tables have been deployed and match the table definitions in schema.rb.



27
28
29
30
31
32
33
34
35
36
37
# File 'lib/batch-kit/database/models.rb', line 27

def self.check_schema(schema)
    schema_file = IO.read("#{File.dirname(__FILE__)}/schema.rb")
    ok, md5 = self.check('SCHEMA', 'schema.rb', schema_file)
    unless ok
        # TODO: Find a better way to update schema for table changes;
        #       This method throws away all history
        schema.drop_tables
        schema.create_tables
        md5.save
    end
end

.for(obj_name, obj_type, digest) ⇒ Object

Locate the MD5 record for the object named obj_name whose type is obj_type.



18
19
20
21
22
# File 'lib/batch-kit/database/models.rb', line 18

def self.for(obj_name, obj_type, digest)
    self.where(Sequel.function(:upper, :object_name) => obj_name.upcase,
               Sequel.function(:upper, :object_type) => obj_type.upcase,
               :md5_digest => digest).first
end