Skip to content

Instantly share code, notes, and snippets.

@elia
Created May 15, 2009 08:20
Show Gist options
  • Save elia/112116 to your computer and use it in GitHub Desktop.
Save elia/112116 to your computer and use it in GitHub Desktop.
commit 1e4c620263077fa03b8fbc11104fde47d041f836
Author: Elia Schito <perlelia@gmail.com>
Date: Fri May 15 10:17:48 2009 +0200
Added Thor::IncludableModule to automagically transform module methods into thor ones.
diff --git a/lib/thor/includable_module.rb b/lib/thor/includable_module.rb
new file mode 100644
index 0000000..8cb821e
--- /dev/null
+++ b/lib/thor/includable_module.rb
@@ -0,0 +1,63 @@
+##
+# Permits to include a module in a Thor class having all the public methods
+# listed as thor tasks. A chance to describe the the command and its usage is
+# given by filling the USAGE (see example) constant in the module, otherwise
+# a default explanation will be provided.
+#
+# NOTE: To use this feature it must be included explicitly with:
+# require 'thor/includable_module'
+#
+#
+# *Example:*
+#
+# require 'thor'
+# require 'thor/includable_module'
+#
+# module ModuleWithThorMethods
+# include Thor::IncludableModule
+#
+# def print text
+# puts text
+# end
+#
+# USAGE = {
+# :print => {
+# :usage => 'print TEXT',
+# :description => 'Prints text.'
+# }
+# }
+# end
+#
+# class CommandLineApp < Thor
+# include ModuleWithThorMethods
+#
+# # ...
+#
+# end
+#
+class Thor
+
+ module IncludableModule
+ def self.included(receiver_module)
+
+ def receiver_module.included(receiver)
+ if receiver.ancestors.include?(Thor)
+ self.public_instance_methods(false).each do |meth|
+ meth = meth.to_s
+ usage = self::USAGES[meth.to_sym] if const_defined? :USAGES
+ if usage.nil?
+ arity = self.instance_method(meth).arity
+ usage = {
+ :usage => "#{meth}#{' [PARAM]' * arity.abs}#{' ...' if arity < 0}",
+ :description => '(No description available for this command)'
+ }
+ end
+ receiver.tasks[meth] = Thor::Task.new(meth, usage[:description], usage[:usage], nil, receiver)
+ end
+ end
+ end
+
+ end
+ end
+
+end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment