lib/bencodr/list.rb in bencodr-1.2.0 vs lib/bencodr/list.rb in bencodr-2.0.0

- old
+ new

@@ -1,55 +1,29 @@ # encoding: UTF-8 module BEncodr module List - module Generic - module InstanceMethods - # Encodes object into a bencoded list. BEncoded strings are length-prefixed base ten followed by a colon and - # the string. Object must implement to_a or to_ary. - # - # [].bencodr #=> "le" - # - # @return [::String] the bencoded list - def bencode - (respond_to?(:to_ary) ? to_ary : to_a).bencode - end - end + def bencode + List.bencode(self) end - - # Registers a class as an object that can be converted into a bencoded list. Class must have instance method to_a - # or to_ary. - # - # class MyClass - # def to_a - # [1, :cat] - # end - # end - # - # BEncodr::Integer.register MyClass - # my_class = MyClass.new - # my_class.bencodr #=> "li1e3:cate" - # - # @param [Class#to_a, Class#to_ary] type the class to add the bencodr instance method to - def self.register(type) - type.send :include, Generic::InstanceMethods + + def self.bencode(arrayable) + ary = coerce(arrayable) + + ary.collect do |element| + Object.bencode(element) + end.unshift(:l).push(:e).join end - - module Array - module InstanceMethods - # Encodes an array into a bencoded list. Bencoded lists are encoded as an 'l' followed by their elements (also - # bencoded) followed by an 'e'. - # - # [:eggs, "ham", 3, 4.1].bencodr #=> "l4:eggs3:hami3ei4ee" - # - # @return [::String] the bencoded list - def bencode - collect do |element| - element.bencode - end.unshift(:l).push(:e).join - end + + private + + def self.coerce(arrayable) + if arrayable.respond_to?(:to_a) + arrayable.to_a + elsif arrayable.respond_to?(:to_ary) + arrayable.to_ary + else + raise BEncodeError, "BEncodr::List.bencode can only be called on an object that provides a to_a or to_ary method." end - - ::Array.send :include, InstanceMethods end end end \ No newline at end of file