Skip to content

Instantly share code, notes, and snippets.

@bravoecho
Forked from mperham/gist:1379464
Created November 20, 2011 15:57
Show Gist options
  • Save bravoecho/1380391 to your computer and use it in GitHub Desktop.
Save bravoecho/1380391 to your computer and use it in GitHub Desktop.
Flexibility with and without Dependency Injection
require 'minitest/autorun'
class TaxCodeBase
class AbstractMethod < StandardError
end
attr_accessor :user_id
def initialize(user_id=nil)
self.user_id = user_id
end
def generate
raise AbstractMethod, "Implement in subclass"
end
end
class UsTaxCode < TaxCodeBase
def generate
"US-#{user_id}"
end
end
class BrazilTaxCode < TaxCodeBase
def generate
"#{user_id}-BR"
end
end
class Customer
attr_accessor :id
def initialize(id)
self.id = id
end
def tax_code(tax_code_generator = UsTaxCode.new)
tax_code_generator.user_id = self.id
tax_code_generator.generate
end
end
class WhimsicalTaxCode < TaxCodeBase
def generate
"****#{user_id.to_s.reverse}****"
end
end
describe Customer do
it "has an american tax code by default" do
Customer.new(123456).tax_code.must_equal "US-123456"
end
it "can compute any type of tax code" do
customer = Customer.new(123456)
customer.tax_code(BrazilTaxCode.new).must_equal "123456-BR"
customer.tax_code(UsTaxCode.new).must_equal "US-123456"
customer.tax_code(WhimsicalTaxCode.new).must_equal "****654321****"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment