diff --git a/lib/moab/file_signature.rb b/lib/moab/file_signature.rb index ec4d6588..a41bf1f7 100644 --- a/lib/moab/file_signature.rb +++ b/lib/moab/file_signature.rb @@ -65,33 +65,28 @@ def initialize(opts = {}) # @return [String] The SHA256 checksum value of the file attribute :sha256, String, :on_save => Proc.new { |n| n.nil? ? "" : n.to_s } - ALL_CHECKSUM_ALGOS = { + KNOWN_ALGOS = { md5: proc { Digest::MD5.new }, sha1: proc { Digest::SHA1.new }, sha256: proc { Digest::SHA2.new(256) } }.freeze def self.from_file(pathname, algos_to_use = nil) - algos_to_use ||= ALL_CHECKSUM_ALGOS.keys + if algos_to_use + raise 'Unrecognized algorithm requested' unless algos_to_use.all? { |a| KNOWN_ALGOS.include?(a) } + else + algos_to_use = KNOWN_ALGOS.keys + end - computed_signatures = algos_to_use.map do |algo_name| - [algo_name, ALL_CHECKSUM_ALGOS[algo_name].call] - end.to_h + signatures = algos_to_use.map { |k| [k, KNOWN_ALGOS[k].call] }.to_h pathname.open("r") do |stream| while (buffer = stream.read(8192)) - computed_signatures.each_value do |digest| - digest.update(buffer) - end + signatures.each_value { |digest| digest.update(buffer) } end end - file_signature = new(size: pathname.size) - computed_signatures.each do |algo_name, digest| - file_signature.instance_variable_set("@#{algo_name}", digest.hexdigest) - end - - file_signature + new(signatures.map { |k, digest| [k, digest.hexdigest] }.to_h.merge(size: pathname.size) ) end # @param type [Symbol,String] The type of checksum