Enables coalesce chaining values on Ruby
Add this line to your application's Gemfile:
gem 'coalescer'
And then execute:
$ bundle install
Or install it yourself as:
$ gem install coalescer
require 'coalescer'
# Tired of this?
foo || bar || baz || 'default' # => 'default'
# Now you can do this
foo.coalesce(bar, baz, 'default') # => 'default'
# Or this
[foo, bar, baz, 'default'].coalesce! # => 'default'
# This is specially useful when you have a lengthy list of possible conditions based on coalescence
def which_price(item)
price = item.price ||
item.order.price ||
item.product.customer_price ||
item.product.price
price.to_d.round(2)
end
# Can be refactored to
def which_price(item)
[item.price,
item.order.price,
item.product.customer_price,
item.product.price].coal!.to_d.round(2)
end
# Noticed something? There are shorthand methods for coalesce and coalesce!
foo.coal(bar, baz, 'default') # => 'default'
[foo, bar, baz, 'default'].coal! # => 'default'
# if you need lazy evaluation, you can pass a proc to coalesce
foo.coalesce(-> { :bar }) # => :bar
# or coalesce!
[foo, bar, baz, -> { :default }].coalesce! # => :default
Bug reports and pull requests are welcome on GitHub at https://github.com/wgirhad/coalescer
This file was mostly generated by Github Co-Pilot, awesome!