Module: Encoder

Defined in:
lib/rbencode.rb

Overview

The encoding class, to encapsulate all encoding behaviour in one module

Class Method Summary collapse

Class Method Details

.encode(data) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbencode.rb', line 25

def self.encode(data)
  if data.is_a? Integer
    encode_int(data)
  elsif data.is_a? String
    encode_string(data)
  elsif data.is_a? Array
    encode_array(data)
  elsif data.is_a? Hash
    encode_hash(data)
  else
    raise UnsupportedDataError
  end
end

.encode_array(data) ⇒ Object



47
48
49
# File 'lib/rbencode.rb', line 47

def encode_array(data)
  "l#{data.collect { |item| encode(item) }.join}e"
end

.encode_hash(data) ⇒ Object



51
52
53
# File 'lib/rbencode.rb', line 51

def encode_hash(data)
  "d#{data.to_a.flatten(1).collect { |item| encode(item) }.join}e"
end

.encode_int(data) ⇒ Object



39
40
41
# File 'lib/rbencode.rb', line 39

def encode_int(data)
  "i#{data}e"
end

.encode_string(data) ⇒ Object



43
44
45
# File 'lib/rbencode.rb', line 43

def encode_string(data)
  "#{data.length}:#{data}"
end