Skip to content

Instantly share code, notes, and snippets.

@christopherslee
Created August 6, 2013 02:33
Show Gist options
  • Save christopherslee/6161539 to your computer and use it in GitHub Desktop.
Save christopherslee/6161539 to your computer and use it in GitHub Desktop.
Intro to DSLs - Part 3 Answer
# lib/part_3/advanced_credit_score.rb
require_relative 'advanced_consumer'
class AdvancedCreditScore
def self.simulate(&block)
consumer = AdvancedConsumer.new
# TODO Part 3
# Once again, use instance eval to invoke the block on the consumer
consumer.instance_eval(&block)
consumer.score
end
end
# lib/part_3/advanced_consumer.rb
require_relative 'monthly_score'
class AdvancedConsumer
attr_reader :accounts, :score
def initialize
@score = 0
@accounts = []
@months = {}
end
def add_account(name)
# TODO Part 3
# Add the account name to the accounts array
@accounts << name
end
def month(name, &actions)
# TODO Part 3
# Store the block, as a proc, into the months hash, where the key is
# the name of the account, and the value is the proc
@months[name] = actions
end
# now calculate each month's score
def score
@months.each_pair do |name, actions|
@score += MonthlyScore.new(accounts).process(actions)
end
@score
end
end
# lib/part_3/monthly_score.rb
class MonthlyScore
attr_reader :paid_balances
def initialize(accounts)
# keep track of which accounts are paid
@paid_balances = {}
accounts.each do |account|
@paid_balances[account.to_sym] = 0
end
end
# iterate over all the paid balances and calculate the monthly score
def calculate_score
score = 0
paid_balances.each_pair do |account, value|
score += (value > 0 ? 1 : -2)
end
score
end
def pay_bill(account_name, amount)
paid_balances[account_name.to_sym] = amount
end
def process(actions)
# TODO part 3
# Convert the actions proc back to a block and use instance eval to
# execute it in the context of this object
#
# Finally, after all the bills have been paid, tally up the score
# for the month using calculate_score
instance_eval(&actions)
calculate_score
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment