Sha256: 66769ab52153cddd9973bacb830a07c596f7310038092fb0fa16aa9d21e6c4a5

Contents?: true

Size: 908 Bytes

Versions: 1

Compression:

Stored size: 908 Bytes

Contents

# frozen_string_literal: true
module JunkDrawer
  # error to be thrown by Callable
  class CallableError < StandardError
  end

  # module to constrain interfaces of classes to just `call`
  module Callable
    def call
      raise NotImplementedError
    end

    # `ClassMethods` defines a class level method `call` that delegates to
    # an instance. It also causes an error to be raised if a public instance
    # method is defined with a name other than `call`
    module ClassMethods
      def call(*args)
        new.(*args)
      end

      def method_added(method_name)
        return if method_name == :call || !public_method_defined?(method_name)

        raise CallableError, "invalid method name #{method_name}, " \
                            'only public method allowed is "call"'
      end
    end

    def self.included(base)
      base.public_send(:extend, ClassMethods)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
junk_drawer-1.0.0 lib/junk_drawer/callable.rb