Class: Moneta::Transforms::Truncate

Inherits:
Moneta::Transform show all
Defined in:
lib/moneta/transforms/truncate.rb

Overview

Transforms strings by truncating them to a certain fixed length (32 bytes or greater). Strings that are longer than the specified length will be MD5 hashed, and their last 32 bytes will be replaced by the hash.

Examples:

Default behaviour

transform = Moneta::Transforms::Truncate.new
transform.encode('testing') # => 'testing'
transform.encode('t' * 33)  # => 'f58e01819308e77aeb32ffa110da0c58'

Specifying a longer maxlen

transform = Moneta::Transforms::Truncate.new(maxlen: 35)
transform.encode('testing') # => 'testing'
transform.encode('t' * 37)  # => 'ttt910ec89be55ea041c93f624557590410'

Instance Method Summary collapse

Methods inherited from Moneta::Transform

#decodable?, #decode, delegate_to, #method_missing, #respond_to_missing?

Constructor Details

#initialize(maxlen: 32, **_) ⇒ Truncate

Returns a new instance of Truncate.

Parameters:

  • maxlen (Numeric) (defaults to: 32)

    length after which a string will be truncated (must be >= 32)



20
21
22
23
24
# File 'lib/moneta/transforms/truncate.rb', line 20

def initialize(maxlen: 32, **_)
  super
  raise ":maxlen must be at least 32" if maxlen < 32
  @maxlen = maxlen
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method in the class Moneta::Transform

Instance Method Details

#encode(value) ⇒ String

Parameters:

  • value (String)

Returns:

  • (String)


28
29
30
31
32
33
34
35
# File 'lib/moneta/transforms/truncate.rb', line 28

def encode(value)
  if value.size >= @maxlen
    digest = ::Digest::MD5.hexdigest(value)
    value[0, @maxlen - digest.size] << digest
  else
    value
  end
end