Sha256: 16b212558a9a7af85ee9eb3ab6034417e470c374e9e50a7666cda571e90376dc

Contents?: true

Size: 707 Bytes

Versions: 5

Compression:

Stored size: 707 Bytes

Contents

# encoding: UTF-8

module BEncodr
  module Dictionary
    def bencode
      Dictionary.bencode(self)
    end
    
    def self.bencode(hashable)
      hash = coerce(hashable)
      
      hash.keys.sort{|a, b| a.to_s <=> b.to_s}.collect do |key|
        BEncodr::String.bencode(key.to_s) + Object.bencode(hash[key])
      end.unshift(:d).push(:e).join
    end
    
    private
    
    def self.coerce(hashable)
      if hashable.respond_to?(:to_h)
        hashable.to_h
      elsif hashable.respond_to?(:to_hash)
        hashable.to_hash
      else
        raise BEncodeError, "BEncodr::Dictionary.bencode can only be called on an object that provides a to_h or to_hash method."
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
bencodr-3.0.2 lib/bencodr/dictionary.rb
bencodr-3.0.1 lib/bencodr/dictionary.rb
bencodr-2.0.1 lib/bencodr/dictionary.rb
bencodr-3.0.0 lib/bencodr/dictionary.rb
bencodr-2.0.0 lib/bencodr/dictionary.rb