Class: OsCtl::Cli::Presentable

Inherits:
Object
  • Object
show all
Defined in:
lib/osctl/cli/presentable.rb

Overview

Container for values that should be treated and presented differently

Presentable is used for OutputFormatter, so that values are sorted by their precise representation, but presented as a formatted string, whose sorting would yield incorrect results.

The formatting is done either by passing a `presenter` callable, or the `formatted` value. If `presenter` is given, it is called to format the value, otherwise `formatted` is used.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(raw, presenter: nil, formatted: nil) ⇒ Presentable

Returns a new instance of Presentable

Parameters:

  • raw (any)

    precise value

  • presenter (Method, Proc)

    called to format the value

  • formatted (String)

    formatted value



21
22
23
24
25
26
# File 'lib/osctl/cli/presentable.rb', line 21

def initialize(raw, presenter: nil, formatted: nil)
  @raw = raw

  v = presenter ? presenter.call(raw) : formatted
  @formatted = v ? v.to_s : raw.to_s
end

Instance Attribute Details

#formattedObject (readonly)

Return the formatted value for presentation



16
17
18
# File 'lib/osctl/cli/presentable.rb', line 16

def formatted
  @formatted
end

#rawObject (readonly)

Return the raw, precise value



13
14
15
# File 'lib/osctl/cli/presentable.rb', line 13

def raw
  @raw
end

Instance Method Details

#coerce(other) ⇒ Object



38
39
40
# File 'lib/osctl/cli/presentable.rb', line 38

def coerce(other)
  [other, raw]
end

#to_json(*args) ⇒ Object

Returns the raw value in JSON



48
49
50
# File 'lib/osctl/cli/presentable.rb', line 48

def to_json(*args)
  raw.to_json(*args)
end

#to_sObject

Returns the formatted value



43
44
45
# File 'lib/osctl/cli/presentable.rb', line 43

def to_s
  formatted
end