diff options
| author | Joshua Peek <josh@joshpeek.com> | 2012-07-23 12:13:08 -0500 |
|---|---|---|
| committer | Joshua Peek <josh@joshpeek.com> | 2012-07-23 12:13:08 -0500 |
| commit | d6fb95b06f960e4cd11cf0aeadfd1a0c52cba060 (patch) | |
| tree | 66d3fff1277328196d75dab671c15da43bee57a0 /lib | |
| parent | db88e143ba96f21502942ad7f39c19307b9a6e02 (diff) | |
Add nested md5 digest
Diffstat (limited to 'lib')
| -rw-r--r-- | lib/linguist/md5.rb | 50 |
1 files changed, 50 insertions, 0 deletions
diff --git a/lib/linguist/md5.rb b/lib/linguist/md5.rb new file mode 100644 index 0000000..4860bcd --- /dev/null +++ b/lib/linguist/md5.rb @@ -0,0 +1,50 @@ +require 'digest/md5' + +module Linguist + module MD5 + # Public: Create deep nested digest of value object. + # + # Useful for object comparsion. + # + # obj - Object to digest. + # + # Returns String hex digest + def self.hexdigest(obj) + digest = Digest::MD5.new + digest_strings(obj).each { |e| digest.update(e) } + digest.hexdigest + end + + # Internal: Get String representations for digest. + # + # obj - Object to digest + # + # Returns an Array of Strings. + def self.digest_strings(obj) + case obj + when String + ["#{obj.class}", "#{obj}"] + when Symbol + ["#{obj.class}", "#{obj}"] + when Integer + ["#{obj.class}", "#{obj}"] + when TrueClass, FalseClass, NilClass + ["#{obj.class}"] + when Array + r = ["#{obj.class}"] + obj.each do |e| + r.concat(digest_strings(e)) + end + r + when Hash + r = ["#{obj.class}"] + obj.map { |k, v| digest_strings([k, v]) }.sort.each do |e| + r.concat(digest_strings(e)) + end + r + else + raise TypeError, "can't convert #{obj.inspect} into String" + end + end + end +end |
