Skip to content

Instantly share code, notes, and snippets.

@gmcabrita
Last active May 13, 2023 18:50
Show Gist options
  • Save gmcabrita/41309011755eff6ddd542b80fb65401c to your computer and use it in GitHub Desktop.
Save gmcabrita/41309011755eff6ddd542b80fb65401c to your computer and use it in GitHub Desktop.

Ruby callable service object

module Callable
  def call
    raise NoMethodError
  end

  def to_proc
    method(:call).to_proc
  end
end

module CallableOperation
  include Callable

  module ClassMethods
    include Callable

    def call(*args, **kwargs, &block)
      new(*args, **kwargs, &block).call
    end
  end

  def self.included(klass)
    klass.extend(ClassMethods)
  end
end

class IntegerIncrementer
  include CallableOperation

  def initialize(i)
    @i = i
  end

  def call
    @i + 1
  end
end

def call_inside_block(&block)
  block.call(1)
end

IntegerIncrementer.call(1)
IntegerIncrementer.new(1).call
call_inside_block(&IntegerIncrementer)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment