Class: Liquid::Tags::ElectricityCost

Inherits:
Liquid::Tag
  • Object
show all
Defined in:
app/lib/liquid/tags/electricity_cost.rb

Overview

Renders a locale-aware electricity operating cost for a given wattage.

Usage in posts/articles:
electricity_cost watts:1000 %
→ "$0.16/hr"

electricity_cost watts:500 period:month %
→ "$5.84/month" (500W × 8hrs/day default × 30 days)

electricity_cost watts:1000 hours_per_day:8 period:month %
→ "$11.69/month"

electricity_cost watts:1000 state:CA %
→ "$0.31/hr" (California-specific rate)

The rate is sourced from ElectricityRate and switches automatically by locale
(en-US → US average, en-CA / fr-CA → Canadian average).
Passing state: or province: overrides the locale rate with the regional rate.

Constant Summary collapse

HOURS_PER_MONTH =

365 days / 12 months × 24 hours

730.0
DEFAULT_HOURS_PER_DAY =
8.0
PERIOD_LABELS =
{
  'hour'  => '/hr',
  'day'   => '/day',
  'month' => '/month'
}.freeze

Instance Method Summary collapse

Constructor Details

#initialize(tag_name, markup, parse_context) ⇒ ElectricityCost

Returns a new instance of ElectricityCost.



34
35
36
37
# File 'app/lib/liquid/tags/electricity_cost.rb', line 34

def initialize(tag_name, markup, parse_context)
  super
  @options = parse_options(markup)
end

Instance Method Details

#render(context) ⇒ Object



39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'app/lib/liquid/tags/electricity_cost.rb', line 39

def render(context)
  locale   = context['locale']&.to_sym || I18n.locale
  watts    = @options[:watts].to_f
  period   = @options[:period] || 'hour'
  region   = @options[:state] || @options[:province]

  return render_error('watts: must be greater than 0') if watts <= 0
  return render_error("Unsupported period: #{period}") unless PERIOD_LABELS.key?(period)

  rate = resolve_rate(locale, region)
  return render_error('No electricity rate available for this locale') if rate.nil?

  cost = calculate_cost(watts, rate, period)
  currency_symbol = resolve_currency_symbol(locale)

  format_output(cost, currency_symbol, period)
end