class UrlStore::CompactEncoder

Public Class Methods

new(options={}) click to toggle source
# File lib/url_store/compact_encoder.rb, line 7
def initialize(options={})
  @secret = options[:secret] || raise('i need a :secret !!')
  @hasher = options[:hasher] || 'SHA1'
  @serializer = options[:serializer] || :marshal
end

Public Instance Methods

decode(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 18
def decode(data)
  hash = data[-hash_length..-1]
  data = data[0...-hash_length]

  if digest(data) == hash
    deserialize extract(data)
  else
    nil
  end
end
encode(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 13
def encode(data)
  data = compress(serialize(data))
  data+digest(data)
end

Private Instance Methods

compress(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 47
def compress(data)
  Base64.encode64( Zlib::Deflate.deflate(data)).gsub("\n",'')
end
deserialize(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 39
def deserialize(data)
  case @serializer.to_sym
  when :yaml then YAML.load(data)
  when :marshal then Marshal.load(data)
  when :json then JSON.load(data)
  end
end
digest(data) click to toggle source

stolen from ActiveSupport

# File lib/url_store/compact_encoder.rb, line 60
def digest(data)
  require 'openssl' unless defined?(OpenSSL)
  OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new(@hasher.to_s), @secret, data)
end
extract(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 51
def extract(data)
  Zlib::Inflate.inflate Base64.decode64(data)
end
hash_length() click to toggle source
# File lib/url_store/compact_encoder.rb, line 55
def hash_length
  digest('x').size
end
serialize(data) click to toggle source
# File lib/url_store/compact_encoder.rb, line 31
def serialize(data)
  case @serializer.to_sym
  when :yaml then data.to_yaml
  when :marshal then Marshal.dump(data)
  when :json then JSON.dump(data)
  end
end