diff options
author | Kasper Timm Hansen <kaspth@gmail.com> | 2015-12-05 00:12:18 +0100 |
---|---|---|
committer | Kasper Timm Hansen <kaspth@gmail.com> | 2015-12-05 00:12:18 +0100 |
commit | 6616724daa1649fa2898228fee44ded879fd4921 (patch) | |
tree | 7a32413f5855514f88d8cf0d7e88147962ef03b8 /railties/lib/rails/commands/command.rb | |
parent | 8bdbf88dfd231f80b8e757b36e77ff72e6b6b83c (diff) | |
parent | 2ddb5997108c4612dd96747fb082ba7f93427a31 (diff) | |
download | rails-6616724daa1649fa2898228fee44ded879fd4921.tar.gz rails-6616724daa1649fa2898228fee44ded879fd4921.tar.bz2 rails-6616724daa1649fa2898228fee44ded879fd4921.zip |
Merge pull request #22457 from ccallebs/rails-commands-infrastructure
Add Rails command infrastructure
Diffstat (limited to 'railties/lib/rails/commands/command.rb')
-rw-r--r-- | railties/lib/rails/commands/command.rb | 78 |
1 files changed, 78 insertions, 0 deletions
diff --git a/railties/lib/rails/commands/command.rb b/railties/lib/rails/commands/command.rb new file mode 100644 index 0000000000..ffd1a50c79 --- /dev/null +++ b/railties/lib/rails/commands/command.rb @@ -0,0 +1,78 @@ +module Rails + module Commands + class Command + attr_reader :argv + + def initialize(argv = '') + @argv = argv + + @option_parser = build_option_parser + @options = {} + end + + def run(task_name) + command_name = self.class.command_name_for(task_name) + + parse_options_for(command_name) + @option_parser.parse! @argv + + if command_instance = command_for(command_name) + command_instance.public_send(command_name) + else + puts @option_parser + end + end + + def self.options_for(command_name, &options_to_parse) + @@command_options[command_name] = options_to_parse + end + + def self.command_name_for(task_name) + task_name.gsub(':', '_').to_sym + end + + def self.set_banner(command_name, banner) + options_for(command_name) { |opts, _| opts.banner = banner } + end + + def exists?(task_name) + command_name = self.class.command_name_for(task_name) + !command_for(command_name).nil? + end + + private + @@commands = [] + @@command_options = {} + + def parse_options_for(command_name) + @@command_options.fetch(command_name, -> {}).call(@option_parser, @options) + end + + def build_option_parser + OptionParser.new do |opts| + opts.on('-h', '--help', 'Show this help.') do + puts opts + exit + end + end + end + + def self.inherited(command) + @@commands << command + end + + def command_for(command_name) + klass = @@commands.find do |command| + command_instance_methods = command.public_instance_methods + command_instance_methods.include?(command_name) + end + + if klass + klass.new(@argv) + else + nil + end + end + end + end +end |