/mighty_tap

A tap for ruby with some extra sugar

Primary LanguageRubyMIT LicenseMIT

mighty_tap

Build Status Test Coverage Code Climate

Ruby's Object#tap is awesome. mighty_tap tries to make it even better by adding some missing features, while maintaining full compatibility with the original. In order to make its usage more pleasant, mighty_tap is defined as an instance method on Object and aliased to Object#mtap.

Why is it even more awesome than tap ?

  • you can give it a method name
  • you can give it arguments and blocks for methods to call
  • despite calling methods on the object itself, you can provide a callable
    • in fact you can provide anything that responds to :call
  • apart from adding features, it acts like the original tap (can act as a drop-in replacement)

Usage

require "mighty_tap"

#
# it can be used just like tap
#
[1,2,3].mtap(&:shift) # => [2,3]

#
# despite the implicit &: block syntax, it can take a method name
#
[1,2,3].mtap(:shift) # => [2,3]

#
# it also takes method arguments
#
[1,2,3].mtap(:shift, 2) # => [3]

#
# if the last argument is a proc, the method is called with the procs block variant
#
[1,2,3].mtap(:map!, -> (number) { number * 2 }) # => [2,4,6]

#
# you can also give it a callable (something that responds to #call)
#
class ArrayDoubler
  def call(array)
    array.map! { |element| element * 2 }
  end
end

[1,2,3].mtap(ArrayDoubler.new) # => [2,4,6]

#
# callables can have arguments and blocks, too
#
class ArrayMultiplier
  def call(array, factor, &reducer)
    multiplied_array = array.map! { |element| element * factor }

    if block_given?
      yield multiplied_array
    end
  end
end

[1,2,3].mtap(ArrayMultiplier.new, 3) # => [3,6,9]
[1,2,3].mtap(ArrayMultiplier.new, 3, -> (array) { array.delete_if { |i| i < 9 } }) # => [9]

#
# this can all be combined with taps original block syntax
#
[1,2,3].mtap(ArrayDoubler.new) do |doubled_array|
  doubled_array.map! { |element| element * element }
end # => [4, 16, 36]

Installation

Add this line to your application's Gemfile:

gem 'mighty_tap'

And then execute:

$ bundle

Or install it yourself as:

$ gem install mighty_tap

Development

After checking out the repo, run bin/setup to install dependencies. Then, run bin/console for an interactive prompt that will allow you to experiment.

To install this gem onto your local machine, run bundle exec rake install. To release a new version, update the version number in version.rb, and then run bundle exec rake release to create a git tag for the version, push git commits and tags, and push the .gem file to rubygems.org.

Contributing

  1. Fork it ( https://github.com/msievers/mighty_tap/fork )
  2. Create your feature branch (git checkout -b my-new-feature)
  3. Commit your changes (git commit -am 'Add some feature')
  4. Push to the branch (git push origin my-new-feature)
  5. Create a new Pull Request