Class: Codify::Encoders::AbstractEncoder

Inherits:
Object
  • Object
show all
Defined in:
lib/codify/encoders/abstract_encoder.rb

Direct Known Subclasses

Base64Encoder, ZlibEncoder

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ AbstractEncoder

Assigns options to instance variable



12
13
14
# File 'lib/codify/encoders/abstract_encoder.rb', line 12

def initialize options = {}
  @options = options.symbolize_keys
end

Class Method Details

.decode(data, options = {}, record = nil) ⇒ Object

Wrapper to easily use encoder for decoding, by automatically constructing one



53
54
55
56
57
# File 'lib/codify/encoders/abstract_encoder.rb', line 53

def self.decode data, options = {}, record = nil
  encoder = new(options)
  encoder.record = record
  encoder.decode(data)
end

.encode(data, options = {}, record = nil) ⇒ Object

Wrapper to easily use encoder for encoding, by automatically constructing one



45
46
47
48
49
# File 'lib/codify/encoders/abstract_encoder.rb', line 45

def self.encode data, options = {}, record = nil
  encoder = new(options)
  encoder.record = record
  encoder.encode(data)
end

Instance Method Details

#decodes?Boolean

Detects whether this encoder can be reversed

Returns:

  • (Boolean)


31
32
33
# File 'lib/codify/encoders/abstract_encoder.rb', line 31

def decodes?
  respond_to?(:decode)
end

#depends_on_record?Boolean

Detects whether any options depend on record attributes. This has implications on the attribute interface. If state information like keys or similar are not constant, then there cannot exist a class method to encode or decode data (ie. encoding must be done on an instance).

Returns:

  • (Boolean)


39
40
41
# File 'lib/codify/encoders/abstract_encoder.rb', line 39

def depends_on_record?
  @options.any? { |option| option.class === Proc || option.class === Symbol }
end

#encode(data) ⇒ Object

Encoders derived from AbstractEncoder should re-implement encode and optionally decode.

Raises:

  • (NotImplementedError)


25
26
27
# File 'lib/codify/encoders/abstract_encoder.rb', line 25

def encode data
  raise NotImplementedError, "Error: #{self.class.name}.encode not implemented!"
end

#record=(record) ⇒ Object

Allow a record to be linked to this encoder (for procs)



18
19
20
# File 'lib/codify/encoders/abstract_encoder.rb', line 18

def record= record
  @record = record
end