module Factree::FactSource

Mixin to help define fact source classes.

Constants

UNKNOWN_FACT
UndefinedFactError
UnknownFactError

Public Class Methods

included(base) click to toggle source
# File lib/factree/fact_source.rb, line 7
def self.included(base)
  base.extend(ClassMethods)
end
to_combined_h(*sources) click to toggle source

Takes several FactSources and returns a single hash containing all of their facts mixed together.

# File lib/factree/fact_source.rb, line 94
def self.to_combined_h(*sources)
  sources.map(&:to_h).inject({}, &:merge)
end

Public Instance Methods

[](fact_name) click to toggle source

Returns the value of the fact, or nil if the value is unknown

# File lib/factree/fact_source.rb, line 48
def [](fact_name)
  fetch(fact_name) { nil }
end
ensure_defined(fact_name) click to toggle source

@api private

# File lib/factree/fact_source.rb, line 70
def ensure_defined(fact_name)
  unless self.class.defined? fact_name
    raise UndefinedFactError, "undefined fact referenced: #{fact_name}"
  end
end
fetch(fact_name, &block) click to toggle source

Returns the value of the fact.

If the value is unknown, then the block will be called with the name of the fact. If no block is supplied, then an UnknownFactError will be raised.

# File lib/factree/fact_source.rb, line 55
def fetch(fact_name, &block)
  ensure_defined fact_name
  fact_proc = self.class.fact_procs[fact_name]

  fact_value = nil
  fact_known = catch(UNKNOWN_FACT) do
    fact_value = instance_eval(&fact_proc)
    true
  end
  return fact_value if fact_known

  fetch_unknown(fact_name, &block)
end
fetch_unknown(fact_name) { |fact_name| ... } click to toggle source

@api private

# File lib/factree/fact_source.rb, line 77
def fetch_unknown(fact_name)
  return yield(fact_name) if block_given?

  raise UnknownFactError, "unknown fact: #{fact_name}"
end
known?(fact_name) click to toggle source

Checks to see if the value of the fact is known.

# File lib/factree/fact_source.rb, line 42
def known?(fact_name)
  fetch(fact_name) { return false }
  true
end
to_h() click to toggle source

A hash mapping all of the known fact names to values.

# File lib/factree/fact_source.rb, line 84
def to_h
  self.class.fact_procs.flat_map { |fact_name, _fact_proc|
    fact_known = true
    fact_value = fetch(fact_name) { fact_known = false }

    fact_known ? [[fact_name, fact_value]] : []
  }.to_h
end
unknown() click to toggle source

Calling this method in a fact proc will signal that the fact's value is unknown.

# File lib/factree/fact_source.rb, line 99
def unknown
  throw UNKNOWN_FACT
end