Class: Safeguard::Hasher

Inherits:
Worker
  • Object
show all
Includes:
Enumerable
Defined in:
lib/safeguard/hasher.rb

Overview

Hashes a set of files.

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods inherited from Worker

callbacks, has_callback

Constructor Details

#initialize(*args) ⇒ Hasher

Initializes a new hasher with the given files. Last argument can be an options hash or ribbon which specifies the hash functions to use:

files = %w(file1 file2 fil3)
Hasher.new *files, :functions => :sha1
Hasher.new *files, :functions => [ :sha1, :md5, :crc32 ]


26
27
28
29
30
31
32
33
34
# File 'lib/safeguard/hasher.rb', line 26

def initialize(*args)
  options = args.extract_ribbon!
  funcs = options.functions? do
    raise ArgumentError, 'No hash functions specified'
  end
  self.functions = [*funcs]
  self.files = args
  initialize_callbacks_from options
end

Instance Attribute Details

#filesObject

The files which will be hashed.



12
13
14
# File 'lib/safeguard/hasher.rb', line 12

def files
  @files
end

#functionsObject

The hash functions to use.



15
16
17
# File 'lib/safeguard/hasher.rb', line 15

def functions
  @functions
end

Instance Method Details

#each(&block) ⇒ Object

Yields file => hash data pairs or returns an enumerator.



59
60
61
# File 'lib/safeguard/hasher.rb', line 59

def each(&block)
  Ribbon.wrap(results).each &block
end

#hash_files!Object

Calculates the hash of each file. Updates the cached hash results.



37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/safeguard/hasher.rb', line 37

def hash_files!
  results = Ribbon.new
  files.each do |file|
    functions.each do |function|
      call_callback before_hashing, file, function
      results[file][function] = result = Safeguard::Digest.file file, function
      call_callback after_hashing, file, function, result
    end
  end
  results = Ribbon.wrap results
  results.wrap_all!
  @results = results
end

#resultsObject

Returns the cached results containing the hashes calculated for each file.

In order to force hash recalculation, call #hash_files!.



54
55
56
# File 'lib/safeguard/hasher.rb', line 54

def results
  @results ||= hash_files!
end