Skip to content

Instantly share code, notes, and snippets.

@harlow
Last active December 15, 2015 00:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save harlow/5175442 to your computer and use it in GitHub Desktop.
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
# 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