evan/memcached — pull request #118 by jason-o-matic (2013-04-08 20:10:00+00:00)
Title: Allow custom encoders

I needed similar functionality to https://github.com/evan/memcached/pull/101 so I took a stab after reading your comment on that PR. It behaves just like the current memcached, but you can pass in an optional encoder to the initializer.

This is how a custom encoder looks in practice:

```
class LzoEncoder
MARSHAL_BYTE = 4
LZO_BYTES = [240, 241]
def self.encode(value)
value = Marshal.dump(value) unless value.is_a?(String)
if value.bytesize > 100
value = LZO.compress(value, 1)
end
value
end
def self.decode(value)
value = decompress(value) if LZO_BYTES.include?(value.getbyte(0))
value = unmarshal(value) if value.getbyte(0) == MARSHAL_BYTE
value
end
def self.decompress(value)
LZO.decompress(value)
rescue LZO::Error => ex
value
end
def self.unmarshal(value)
Marshal.load(value)
rescue TypeError, ArgumentError => ex
value
end
end
```

And then I'll pass that in as an option to the memcached initializer.
```
options = some_other_options.merge(:encoder => LzoEncoder)
$memcache = Memcached::Rails.new(servers, options)
```