lib/prezzo/explainable.rb in prezzo-0.4.1 vs lib/prezzo/explainable.rb in prezzo-0.5.0

- old
+ new

@@ -5,29 +5,37 @@ base.extend(ClassMethods) end end module ClassMethods - def explain_with(*component_names) - define_method(:explain) do - explanation = { - total: calculate, - } + def explain_with(*component_names, **options) + @explained_components ||= {} + component_names.each do |component_name| + @explained_components[component_name] = options + end + end - components = component_names.each_with_object({}) do |component, acc| - value = send(component) - if self.class.respond_to?(:components) && self.class.components.include?(component) - value = cached_components[component] - end - value = value.explain if value.respond_to?(:explain) - value = value.calculate if value.respond_to?(:calculate) - acc[component] = value - end + attr_reader :explained_components + end - explanation[:components] = components unless components.empty? + def explain + explained_components = self.class.explained_components || {} - explanation + explanation = { + total: calculate, + components: {}, + } + + explained_components.each do |component, options| + value = send(component) + if self.class.respond_to?(:components) && self.class.components.include?(component) + value = cached_components[component] end + value = value.explain if value.respond_to?(:explain) && options.fetch(:resursive, true) + value = value.calculate if value.respond_to?(:calculate) + explanation[:components][component] = value end + + explanation end end end