Trick

An attempt to gracefully enhance capabilities of ruby objects.

Installation

Add this line to your application's Gemfile:

gem 'trick'

And then execute:

$ bundle

Or install it yourself as:

$ gem install trick

Usage

1. Turn something into a proc

Point = Struct.new :coords do
  extend Trick::Value

  def radius
    Math.sqrt(coords[0]**2 + coords[1]**2)
  end
end

# create a list with proclike factory
points = [[3, 4], [8, 6]].map(&Point)
points.map(&:radius) # => [5, 10]

module NormalizedDistance
  extend Trick::Function

  # main function method
  def call(divisor, point)
    point.radius / divisor * (inc_order? ? 10 : 100)
  end

  # use private methods in your function
  private def inc_order?
    point.coords[1] > point.coords[0]
  end
end

# map points with curried function
NormalizedDistance[5] # => curried proc
points.map(&NormalizedDistance[5]) # => [10, 200]

1.1 Currying

# class currying:
class Sum
  extend Trick::Value

  attr_reader :sum

  def initialize(a, b)
    @sum = a + b
  end
end

Sum[41] # => curried proc
Sum[1, 2].sum # => 3

# struct currying:
A = Struct.new :x, :y do
  extend Trick::Value
end

A[1] # => curried proc
A[1, 2] # => struct A[1, 2]

Contributing

  1. Fork it ( https://github.com/focused/trick/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