Created
June 12, 2019 11:32
-
-
Save rogerleite/80e9e2b8d943387a65fc9ea71c408097 to your computer and use it in GitHub Desktop.
Example of defensive ruby
This file contains 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
# 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
https://medium.com/@rogerleite/%C3%B3timas-dicas-jessica-chaves-%C3%B3timo-post-b38367c1898a