Class: Scl::Auto

Inherits:
Format show all
Defined in:
lib/scl/formats/auto.rb

Constant Summary

Constants inherited from Format

Format::AUTO, Format::BASE64, Format::BINARY, Format::HEX, Format::QRCODE, Format::STDOUT, Format::WORDS

Instance Method Summary collapse

Methods inherited from Format

#name, #output, #read

Instance Method Details

#decode(data) ⇒ Object



12
13
14
15
16
17
18
19
20
21
# File 'lib/scl/formats/auto.rb', line 12

def decode(data)
  png = Regexp.new("\x89PNG".force_encoding("binary"))
  if /^#{png}/ === data.force_encoding("binary")
    Scl::Format::QRCODE.decode(data)
  elsif data[/[^A-Za-z0-9\+\/\n=]/]
    Scl::Format::BINARY.decode(data)
  else
    Scl::Format::BASE64.decode(data)
  end
end

#encode(data) ⇒ Object



3
4
5
6
7
8
9
10
# File 'lib/scl/formats/auto.rb', line 3

def encode(data)
  sorted = (data.force_encoding("binary").chars.map(&:ord).uniq.sort) - [10]
  if sorted.first < 32 || sorted.max > 126
    Scl::Format::BASE64.encode(data)
  else
    Scl::Format::BINARY.encode(data)
  end
end