module EhPrize
EhPrize — parse CTF prize strings into comparable USD values for sorting. Public: parse_amount, max_usd, format_label Depends: (stdlib only) Tests: test/lib/eh_prize_test.rb
Constants
- AMOUNT_PATTERN
- USD_PER_EUR
-
Fixed rates for sort ordering only — not live FX.
- USD_PER_GBP
- USD_PER_INR
Public Instance Methods
Source
# File lib/eh_prize.rb, line 80 def best_label(*texts) best_usd = 0.0 label = nil each_amount_fragment(*texts) do |fragment| parsed = parse_amount(fragment) next unless parsed && parsed[:usd] > best_usd best_usd = parsed[:usd] label = parsed[:label] end label end
Source
# File lib/eh_prize.rb, line 93 def each_amount_fragment(*texts) return enum_for(:each_amount_fragment, *texts) unless block_given? Array(texts).each do |text| remainder = text.to_s while (match = remainder.match(AMOUNT_PATTERN)) yield match[0] remainder = remainder[match.end(0)..] end end end
Source
# File lib/eh_prize.rb, line 116 def format_commas(value) if (value % 1).zero? integer = value.to_i integer.to_s.reverse.gsub(/(\d{3})(?=\d)/, '\\1,').reverse else format("%.2f", value) end end
Source
# File lib/eh_prize.rb, line 105 def format_label(usd, original) label = original.to_s.strip return label unless label.empty? "$#{format_commas(usd.round)}" end
Source
# File lib/eh_prize.rb, line 71 def max_usd(*texts) best = 0.0 each_amount_fragment(*texts) do |fragment| parsed = parse_amount(fragment) best = parsed[:usd] if parsed && parsed[:usd] > best end best end
Source
# File lib/eh_prize.rb, line 112 def normalize_number(text) text.to_s.delete(",").to_f end
Source
# File lib/eh_prize.rb, line 34 def parse_amount(fragment) match = fragment.to_s.match(AMOUNT_PATTERN) return nil unless match if match[:usd_prefix] value = normalize_number(match[:usd_amount]) return { usd: value, label: "$#{format_commas(value)}" } end if match[:eur_prefix] || match[:eur_suffix] value = normalize_number(match[:eur_amount1] || match[:eur_amount2]) return { usd: value * USD_PER_EUR, label: "\u20ac#{format_commas(value)}" } end if match[:gbp_prefix] value = normalize_number(match[:gbp_amount]) return { usd: value * USD_PER_GBP, label: "\u00a3#{format_commas(value)}" } end if match[:inr_k_amount] value = match[:inr_k_amount].to_f * 1000.0 return { usd: value * USD_PER_INR, label: "#{match[:inr_k_amount]}K INR" } end if match[:inr_amount] value = normalize_number(match[:inr_amount]) return { usd: value * USD_PER_INR, label: "\u20b9#{format_commas(value)}" } end if match[:usd_word_amount] value = normalize_number(match[:usd_word_amount]) return { usd: value, label: "$#{format_commas(value)}" } end nil end