Sha256: ae3618ba0c7b9e0c77da166fd5b402c586cb4d0f4ae55398e3cbb1266ee8870b
Contents?: true
Size: 1.97 KB
Versions: 12
Compression:
Stored size: 1.97 KB
Contents
require File.expand_path(File.join(File.dirname(__FILE__), '..', 'fathom')) module Fathom class ValueDescription class << self # Returns a simple accessor for the node, so that the value description works a little like an OpenStruct. def define_node_accessor(node, method = :node) define_method(node.name_sym) do node.send(method) end end end attr_reader :nodes, :last_process def initialize(*nodes, &block) assert_nodes(nodes) @process_block = block if block_given? end def add_node(node, method = :rand) assert_node(node, method) end def process prepare_process @process_block ? @process_block.call(@last_process) : default_process(@last_process) end protected def prepare_process @last_process = self.nodes.inject(OpenStruct.new) do |o, node| o.table[node.name_sym] = self.send(node.name_sym) o end end def default_process(obj) obj.values.inject(0.0) do |s, e| s += e end end def assert_nodes(nodes) @nodes ||= [] nodes.each do |node| case node when Hash assert_node_from_hash(node) else assert_node(node) end end end def assert_node(node, method = :rand) raise ArgumentError, "Must provide a node that can respond to name" unless node.respond_to?(:name) @nodes ||= [] self.class.define_node_accessor(node, method) @nodes << node end # Takes a node => :value_hash signature for the values in the hash def assert_node_from_hash(hash) hash.each do |node, value_method| assert_node(node, value_method) end end end end if __FILE__ == $0 include Fathom # TODO: Is there anything you want to do to run this file on its own? # ValueDescription.new end
Version data entries
12 entries across 12 versions & 1 rubygems