Class: Factbase::FactAsYaml

Inherits:
Object
  • Object
show all
Defined in:
lib/factbase/fact_as_yaml.rb

Overview

Single fact to YAML converter.

This class helps converting a single fact to YAML format, for example:

require 'factbase/fact_as_yaml'
fb = Factbase.new
f = fb.query('(eq foo 42)').to_a.first
puts Factbase::FactAsYaml.new(f).to_s
Author

Yegor Bugayenko ([email protected])

Copyright

Copyright © 2024-2025 Yegor Bugayenko

License

MIT

Instance Method Summary collapse

Constructor Details

#initialize(fact) ⇒ FactAsYaml

Constructor.



24
25
26
# File 'lib/factbase/fact_as_yaml.rb', line 24

def initialize(fact)
  @fact = fact
end

Instance Method Details

#to_sString

Convert the fact to YAML.

Returns:

  • (String)

    The fact in YAML format



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# File 'lib/factbase/fact_as_yaml.rb', line 30

def to_s
  props = @fact.all_properties
  hash = {}
  props.each do |p|
    v = @fact[p]
    hash[p] = v.is_a?(Array) ? v : [v]
  end
  hash.sort.to_h.map do |k, vv|
    [
      k,
      ': ',
      if vv.one?
        v_to_s(vv.first)
      else
        [
          '[',
          vv.map { |v| v_to_s(v) }.join(', '),
          ']'
        ]
      end
    ].zip.join
  end.join("\n")
end