Module: Crunchr
- Defined in:
- lib/crunchr.rb
Overview
Crunch statistics with fun
Defined Under Namespace
Modules: ClassMethods
Class Method Summary collapse
Instance Method Summary collapse
-
#calculate(key) ⇒ Object
given a string like ‘keys - doors’, returns the amount of spare keys.
- #checked(val) ⇒ Object
- #delta(other) ⇒ Object
-
#fetch(key) ⇒ Object
Get the value from the data.
- #zero ⇒ Object
Class Method Details
.included(base) ⇒ Object
9 10 11 |
# File 'lib/crunchr.rb', line 9 def self.included(base) base.extend(ClassMethods) end |
Instance Method Details
#calculate(key) ⇒ Object
given a string like ‘keys - doors’, returns the amount of spare keys
80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 |
# File 'lib/crunchr.rb', line 80 def calculate(key) (left, op, right) = key.split(/\s/) left = ( left =~ /[^\d.]/ ? self.fetch(left) : BigDecimal.new(left) ) || zero() right = ( right =~ /[^\d.]/ ? self.fetch(right) : BigDecimal.new(right) ) || zero() op = op == ":" ? "/" : op op = op == "x" ? "*" : op # make sure at least 1 hand is a float left *= 1.0 if [left.class, right.class].include?(Fixnum) value = ( left.send(op, right) ) rescue zero() return checked(value) end |
#checked(val) ⇒ Object
14 |
# File 'lib/crunchr.rb', line 14 def checked(val); self.class.checked(val); end |
#delta(other) ⇒ Object
16 17 18 19 20 21 22 23 24 25 26 |
# File 'lib/crunchr.rb', line 16 def delta(other) return nil unless other.respond_to?(:data) && !other.data.is_a?(Hash) return nil unless self.data.is_a?(Hash) delta = self.class.new( :data => self.data.delta(other.data) ) # make it read-only delta.readonly! if delta.respond_to?(:readonly!) return delta end |
#fetch(key) ⇒ Object
Get the value from the data
# Given a data tree that looks like
{ number: 1
collection: {
depth: 2
}
list: [ 1, 2, 3 ]
}
fetch("number") # => 1
fetch("collection/depth") # => 2
fetch("n'existe pas") # => nil
fetch("collection") # => { depth: 2 }
fetch("list") # => nil - NaN && !Hash
When you supply a calculation to fetch, it will delegate to calculate
fetch("number : collection") # => 0.5 (1 / 2)
47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 |
# File 'lib/crunchr.rb', line 47 def fetch(key) return calculate(key) if key =~ / [*\/:x+-] / key = key.split(/\//).collect(&:to_sym) if key =~ /\// value = nil # fetch directly if [String, Symbol].include?(key.class) if self.data.has_key?(key) value = self.data.fetch(key) else value = self.data.fetch(key.to_sym) rescue nil end else value = self.data key.each do |sub| value = value.fetch(sub) rescue nil end end if value.is_a?(Numeric) || value.is_a?(Hash) return value end rescue => ex if self.class.respond_to?(:logger) && !self.class.logger.nil? self.class.logger.error "Error in #{self.class}.fetch(#{key}) for #{data}" end end |
#zero ⇒ Object
13 |
# File 'lib/crunchr.rb', line 13 def zero; self.class.zero; end |