Created
February 6, 2014 18:04
-
-
Save bagilevi/8849399 to your computer and use it in GitHub Desktop.
Ruby mixin that makes runnable classes available as methods
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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