Created
February 10, 2017 20:16
-
-
Save benzittlau/e828bc97a9c066517416548e5813bd9a to your computer and use it in GitHub Desktop.
Merging defaults with options hash in a ruby function
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
# Related area of style guide: https://github.com/GetJobber/ruby-style-guide#hash-fetch-defaults | |
# Pros: Is succinct and intuitive | |
# Cons: Doesn't work for false values | |
def default_one(options) | |
options[:foo] ||= 'foo' | |
options[:bar] ||= 'bar' | |
end | |
# Pros: Handles false without issue, is succient | |
# Cons: Less intuitive if you're not familiar with the behaviour of merge. This line is somewhat cryptic: options = defaults.merge(options) | |
# Involves shadowing "options" with a merged version of options. | |
def default_two(options) | |
defaults = {:foo => 'foo', :bar => 'boo'} | |
options = defaults.merge(options) | |
end | |
# Source: http://stackoverflow.com/questions/977535/whats-a-nice-clean-way-to-use-an-options-hash-with-defaults-values-as-a-paramet | |
# Pros: Handles false without issue, is even more succient than option 2, maybe more intuitive than option 2 | |
# Cons: You're even less likely to intuitively know what a `reverse_merge` is than `merge`, but you can probably guess from context | |
def default_three(options) | |
options.reverse_merge!{ | |
:foo => 'foo', | |
:bar => 'bar' | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Decision, we'll run with default_six as our convention for now.