Class: OsCtl::Lib::Cli::Presentable

Inherits:
Object
  • Object
show all
Defined in:
lib/libosctl/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, **opts) ⇒ Presentable

Returns a new instance of Presentable.

Parameters:

  • raw (any)

    precise value

  • opts (Hash)

Options Hash (**opts):

  • presenter (Method, Proc)

    called to format the value

  • formatted (String)

    formatted value

  • exported (any)

    value used for dump to JSON



26
27
28
29
30
31
32
33
34
35
# File 'lib/libosctl/cli/presentable.rb', line 26

def initialize(raw, **opts)
  @raw = raw

  formatted = opts[:formatted]

  v = opts.has_key?(:presenter) ? opts[:presenter].call(raw) : formatted
  @formatted = v ? v.to_s : raw.to_s

  @exported = opts.has_key?(:exported) ? opts[:exported] : raw
end

Instance Attribute Details

#exportedObject (readonly)

Return the value which is used for JSON representation



19
20
21
# File 'lib/libosctl/cli/presentable.rb', line 19

def exported
  @exported
end

#formattedObject (readonly)

Return the formatted value for presentation



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

def formatted
  @formatted
end

#rawObject (readonly)

Return the raw, precise value



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

def raw
  @raw
end

Instance Method Details

#coerce(other) ⇒ Object



47
48
49
# File 'lib/libosctl/cli/presentable.rb', line 47

def coerce(other)
  [other, raw]
end

#roundObject

Forward ‘round` call to the raw value



62
63
64
# File 'lib/libosctl/cli/presentable.rb', line 62

def round(*)
  raw.round(*)
end

#to_jsonObject

Returns the raw value in JSON



57
58
59
# File 'lib/libosctl/cli/presentable.rb', line 57

def to_json(*)
  exported.to_json(*)
end

#to_sObject

Returns the formatted value



52
53
54
# File 'lib/libosctl/cli/presentable.rb', line 52

def to_s
  formatted
end