Skip to content

Instantly share code, notes, and snippets.

@bagilevi
Created February 6, 2014 18:04
Show Gist options
  • Select an option

  • Save bagilevi/8849399 to your computer and use it in GitHub Desktop.

Select an option

Save bagilevi/8849399 to your computer and use it in GitHub Desktop.
Ruby mixin that makes runnable classes available as methods
require 'active_support/core_ext'
# Makes runnable classes available as methods.
#
# Example:
#
# class FirstClass
# include RunnableClassesAsMethods
# class AddNumbers
# def initialize(a, b); @a, @b = a, b end
# def run; @a + @b end
# end
# end
#
# puts FirstClass.new.add_numbers(1, 2) # => 3
#
# class SecondClass
# extend RunnableClassesAsMethods
# class AddNumbers
# def initialize(a, b); @a, @b = a, b end
# def run; @a + @b end
# end
# end
#
# puts SecondClass.add_numbers(2, 3) # => 5
#
module RunnableClassesAsMethods
def method_missing(m, *args, &block)
klass =
begin
(self.is_a?(Module) ? self : self.class).const_get(m.to_s.camelize)
rescue NameError
end
if klass
logger.debug "#{m}(#{args.short_inspect})" if respond_to?(:logger)
klass.new(*args).run
else
super
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment