lib/bencode.rb in bencode-0.3.2 vs lib/bencode.rb in bencode-0.4.0
- old
+ new
@@ -19,11 +19,11 @@
# 0.bencode #=> "i0e"
#
# === Strings
#
# Strings are sequences of zero or more bytes. They are encoded as
-# <i><length>:<contents></i>, where _length_ is the length of _contents_. _length_
+# <i><length>:<contents></i>, where _length_ is the length of _contents_. _length_
# must be non-negative.
#
# "".bencode #=> "0:"
# "foo".bencode #=> "3:foo"
#
@@ -69,11 +69,11 @@
class Object
#
# Raises an exception. Subclasses of Object must themselves
# define meaningful #bencode methods.
def bencode
- raise BencodeError, self.class
+ raise BencodeError, "object cannot be bencoded"
end
end
class Integer
#
@@ -89,11 +89,11 @@
end
class String
#
# Bencodes the String object. Bencoded strings are represented
- # as +x+:+y+, where +y+ is the string and +x+ is the length of the
+ # as <code>x</code>:<code>y</code>, where +y+ is the string and +x+ is the length of the
# string.
#
# "foo".bencode #=> "3:foo"
# "".bencode #=> "0:"
#
@@ -128,11 +128,13 @@
# +lxe+, where +x+ is zero or more bencoded objects.
#
# [1, "foo"].bencode #=> "li1e3:fooe"
#
def bencode
- "l#{map{|obj| obj.bencode}.join('') }e"
+ "l#{map{|obj| obj.bencode }.join('')}e"
+ rescue BencodeError
+ raise BencodeError, "list items must be bencodable"
end
end
class Hash
#
@@ -140,12 +142,18 @@
# +dxe+, where +x+ is zero or a power of two bencoded objects.
# each key is immediately followed by its associated value.
# All keys must be strings. The keys of the bencoded hash will
# be in lexicographical order.
def bencode
- pairs = sort.map{|key, val| [key.to_str.bencode, val.bencode]}
+ pairs = sort.map{|key, val| [key.to_str.bencode, val.bencode] }
"d#{pairs.join('')}e"
+ rescue NoMethodError => error
+ if error.name == :to_str
+ raise BencodeError, "dictionary keys must be strings"
+ else
+ raise
+ end
end
end
class IO
def self.bdecode(filename)
@@ -163,18 +171,10 @@
def bencode
read.chomp.bencode
end
end
-class BencodeError < StandardError
- def initialize(object_class = nil) # :nodoc:
- @object_class = object_class
- end
-
- def to_s # :nodoc:
- "could not bencode #{@object_class}"
- end
-end
+class BencodeError < StandardError; end
class BdecodeError < StandardError; end
module Bencode
class << self