Last active
December 15, 2015 00:49
-
-
Save harlow/5175442 to your computer and use it in GitHub Desktop.
Playing around with alternatives to this post: http://kresimirbojcic.com/2011/11/19/dependency-injection-in-ruby.html
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# app/models/customer.rb | |
class Customer | |
attr_reader :id, :country | |
def initialize(attrs = {}) | |
@id = attrs[:id] | |
@country = attrs[:country] | |
end | |
def tax_code | |
TaxCodes.find(country).tax_code(id) | |
end | |
end | |
# app/models/tax_codes.rb | |
module TaxCodes | |
def self.find(country) | |
begin | |
TaxCodes.const_get(country) | |
rescue NameError | |
raise "Tax codes for #{country} not supported" | |
end | |
end | |
end | |
# app/models/tax_codes/united_states.rb | |
module TaxCodes | |
class USA | |
def self.tax_code(id) | |
"US-#{id}" | |
end | |
end | |
end | |
# app/models/tax_codes/brazil.rb | |
module TaxCodes | |
class Brazil | |
def self.tax_code(id) | |
"#{id}-BR" | |
end | |
end | |
end | |
puts Customer.new(country: 'USA', id: '1234').tax_code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment