diff options
author | Kasper Timm Hansen <kaspth@gmail.com> | 2015-12-06 14:23:28 +0100 |
---|---|---|
committer | Kasper Timm Hansen <kaspth@gmail.com> | 2015-12-06 14:23:28 +0100 |
commit | 5da05c3e6be52331899742db0dbd6d38e4fdeb1e (patch) | |
tree | 23e3d265994cdf1a6a3240a3182963a263895f25 /railties/lib/rails/command.rb | |
parent | 93ee1b1021c974b9dd5ceee7166698af902cf34c (diff) | |
download | rails-5da05c3e6be52331899742db0dbd6d38e4fdeb1e.tar.gz rails-5da05c3e6be52331899742db0dbd6d38e4fdeb1e.tar.bz2 rails-5da05c3e6be52331899742db0dbd6d38e4fdeb1e.zip |
Ditch `Commands` namespace for base command.
Reading `Rails::Commands::Command` feels excessive. Especially if users can subclass command
to write their own commands — which I'd like to aim for.
Switch to `Rails::Command` before we get too far into things.
Diffstat (limited to 'railties/lib/rails/command.rb')
-rw-r--r-- | railties/lib/rails/command.rb | 70 |
1 files changed, 70 insertions, 0 deletions
diff --git a/railties/lib/rails/command.rb b/railties/lib/rails/command.rb new file mode 100644 index 0000000000..6587984b53 --- /dev/null +++ b/railties/lib/rails/command.rb @@ -0,0 +1,70 @@ +require 'rails/commands/commands_tasks' + +module Rails + class Command + attr_reader :argv + + def initialize(argv = []) + @argv = argv + + @option_parser = build_option_parser + @options = {} + end + + def self.run(task_name, argv) + command_name = command_name_for(task_name) + + if command = command_for(command_name) + command.new(argv).run(command_name) + else + Rails::CommandsTasks.new(argv).run_command!(task_name) + end + end + + def run(command_name) + parse_options_for(command_name) + @option_parser.parse! @argv + + public_send(command_name) + end + + def self.options_for(command_name, &options_to_parse) + @@command_options[command_name] = options_to_parse + end + + def self.set_banner(command_name, banner) + options_for(command_name) { |opts, _| opts.banner = banner } + end + + private + @@commands = [] + @@command_options = {} + + def parse_options_for(command_name) + @@command_options.fetch(command_name, proc {}).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 self.command_name_for(task_name) + task_name.gsub(':', '_').to_sym + end + + def self.command_for(command_name) + @@commands.find do |command| + command.public_instance_methods.include?(command_name) + end + end + end +end |