DEV Community

Kelly Stannard
Kelly Stannard

Posted on

Procable Classes

This is I think a good combination of cheap and simple for use in a more functional style of ruby.

Very simple cases

class AddOne
  singleton_class.attr_accessor :to_proc
  self.to_proc = ->(x) { x + 1 }
  define_singleton_method(:call, to_proc)
end

1.then(&AddOne) #=> 2
AddOne.call(1) #=> 2
Enter fullscreen mode Exit fullscreen mode

More complex cases

Most times you will want to use Object instances as they make refactoring easier.

class AddTwo
  singleton_class.attr_accessor :to_proc
  self.to_proc = ->(x) { new(x).call }
  define_singleton_method(:call, to_proc)

  def initialize(x)
    @x = x
  end
  def call
    @x + 2
  end
end

1.then(&AddTwo) #=> 3
AddTwo.call(1) #=> 3
Enter fullscreen mode Exit fullscreen mode

edit: changed class << self to singleton_class

Top comments (0)