Skip to content

Instantly share code, notes, and snippets.

@rogerleite
Created June 12, 2019 11:32
Show Gist options
  • Save rogerleite/80e9e2b8d943387a65fc9ea71c408097 to your computer and use it in GitHub Desktop.
Save rogerleite/80e9e2b8d943387a65fc9ea71c408097 to your computer and use it in GitHub Desktop.
Example of defensive ruby
# example 1: adopting default values and trying to not break things
def adapter(action)
action = action.to_sym unless action.is_a?(Symbol)
batch = {
active_products: "ProductsActive",
inactive_products: "ProductsInactive",
download_products: "ProductsDownload"
}
batch.fetch(action, "UnknownAction")
end
# example 2: be explicit about your contracts
def adapter(action)
unless action.is_a?(Symbol)
raise ArgumentError, "action parameter must be a symbol. Action: #{action.to_s}"
end
batch = {
active_products: "ProductsActive",
inactive_products: "ProductsInactive",
download_products: "ProductsDownload"
}
batch.fetch(action) do |value|
raise ArgumentError, "Unexpected value for action: #{value}"
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment