Skip to content

Instantly share code, notes, and snippets.

@amolpujari
Last active December 11, 2015 04:39
Show Gist options
  • Select an option

  • Save amolpujari/4546814 to your computer and use it in GitHub Desktop.

Select an option

Save amolpujari/4546814 to your computer and use it in GitHub Desktop.
require 'active_support/core_ext'
class PricingCalc
attr_reader :bill, :usage
def initialize entire_usage
@bill = 0
@usage = 0
@entire_usage = entire_usage
end
def add amount
puts "adding #{amount}"
@bill += amount
end
def for_month_of months
months = months.split(',') # => 'Jan, Feb, Oct'
months.each do |month|
date = DateTime.parse month
consider_usage_between date, date + 1.month
end
end
def during hours
hours.split(' ') # => ['6am', 'to', '9am']
consider_usage_during hours[0], hours[2]
end
def on days
days = days.split(',') # => ['Sep 10', 'Jun 13']
days.each do |day|
date = DateTime.parse day
consider_usage_between date, date + 1.day
end
end
private
def consider_usage_between date_from, date_to
# this will add the usage between given date to @usage
# for example
@usage = 200
end
def consider_usage_during hours_from, hours_to
# this will filterout the usage between given hours
@usage = 300
end
end
class PricingDSL
def self.apply_dsl klass, args, &block
dsl = klass.new args
dsl.instance_eval &block if block_given?
end
end
PricingDSL.apply_dsl(PricingCalc, 400) do
add 10
for_month_of "Jan, Feb, Oct"
add usage*0.06454 if usage >= 0 and usage <= 500
on "Sep 10, Jun 13"
during "7pm to 4pm"
add usage*(-0.015)
puts bill
end
# sample output
#
#amol@sinhgad:~/alfredo$ ruby pricing_calc.rb
#adding 10
#adding 12.908
#adding -4.5
#18.408
#amol@sinhgad:~/alfredo$
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment