module Eco module Data module FuzzyMatch class Score < Struct.new(:score, :total) def ratio(decimals = 6) tot = self.total; sc = self.score tot = tot && tot > 0 ? tot : 1 sc = sc && sc > 0 ? sc : 0 (sc.to_f / tot).round(decimals) end def percent(decimals = 3) (100 * ratio).round(decimals) end def increase(value = 1) self.score += value raise "Score #{self.score} (increase: #{value}) can't be greater than total #{self.total}" if self.score > self.total self.score end def increase_total(value) self.total += value end def values_at(*keys) keys.map do |key| self.send(key) if self.respond_to?(key) end end # Merges 2 Score instance objects def merge(scr) Score.new(*values_at(:score, :total)).merge!(scr) end def merge!(scr) raise "Expecting Score object. Given: #{scr.class}" unless scr.is_a?(Score) increase_total(scr.total) increase(scr.score) self end end end end end