Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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