Class: PersistentHash::Formatter

Inherits:
Object
  • Object
show all
Defined in:
app/models/persistent_hash/formatter.rb

Overview

Formatters are used to create the readable_value attribute for values stored in the Hash.

Class Method Summary collapse

Class Method Details

.add(clazz, proc) ⇒ Object

specify how the human-readable version of the item should be generated

Examples:

PersistentHash::Formatter.add(
  Time,
  ->(val) { val.iso8601 }
)

Parameters:

  • clazz (Class)

    The formatter will receive instances of this class.

  • proc (Proc)

    A proc which receives an instance of clazz and returns a string representation of that instance.



20
21
22
23
# File 'app/models/persistent_hash/formatter.rb', line 20

def self.add(clazz, proc)
  @formatters[clazz] = proc
  true
end

.format(value) ⇒ String

create a human-readable version of value for storage in the db

If a specific formattation proc has been supplied for the value’s class via ‘add`, that proc will be invoked. Otherwise, the result of the value’s ‘to_s` method will be returned.

Returns:

  • (String)

    A string representation of value.



32
33
34
35
36
37
38
39
# File 'app/models/persistent_hash/formatter.rb', line 32

def self.format(value)
  formatter = @formatters[value.class]
  if formatter
    formatted = formatter.call(value)
  else
    formatted = value.to_s
  end
end

.reset!Object

forget all current formatters



42
43
44
45
# File 'app/models/persistent_hash/formatter.rb', line 42

def self.reset!
  @formatters = {}
  true
end