【问题标题】:Rails 4 optparse invalid_optionRails 4 optparse invalid_option
【发布时间】:2015-09-21 00:38:23
【问题描述】:

我有以下代码。使用 -c 1 有效,但使用 -e 1 会导致无输出,使用 --from_date 会导致“invalid_option”错误。我做错了什么?

require 'optparse'
namespace :schedule do |args|
  desc "Create schedule entries for recurring events"
  task :create_recurring => :environment do 
    options = {}
    optparse = OptionParser.new(args) do |opts|
      opts.on("--from_date {from_date}", "Date to start creating Schedules") do |from_date|
        options[:from_date] = from_date
      end
      opts.on("-e", "--event_id {event_id}", "Event to create Schedules for") do |event_id|
        options[:event_id] = event_id
      end
      opts.on("-c","--calendar_id {calendar_id}", "Calendar to create Schedules for") do |calendar_id|
        options[:calendar_id] = calendar_id
      end
    end
    begin 
      optparse.parse!
    rescue OptionsParser::InvalidOption => e
      puts "invalid option : e.inspect"
    end

    puts "options #{options.inspect}"
  end
end

【问题讨论】:

    标签: ruby ruby-on-rails-4 rake


    【解决方案1】:

    使用您的 Rakefile,我已经设法让它工作(我有 Rake 0.9.6;显然是 newer Rake versions may have issues?):

    rake schedule:create_recurring -- -c1 -e42 --from_date=foo
    

    这个输出:

    options {:calendar_id=>"1", :event_id=>"42", :from_date=>"foo"}
    

    【讨论】:

    • 我在链接的 StackOverflow 中将 optparse 行更改为:optparse.parse!(ARGV[2..-1]),因为我使用的是 Rake 10.4.2,但仍然不行。 :\ 适用于 -c,但不适用于 -e 或 --from_date。
    • 我将 Rake 更新到 10.4.2。使用optparse.parse!(ARGV[2..-1]),它对我有用,但我在编写它时使用了rake 命令完全。 (-c1-e42 中没有空格,并且使用= 代替--from_date=foo 中的空格。如果使用空格,rake 会哭。)
    猜你喜欢
    • 2011-11-22
    • 2012-07-30
    • 2017-01-20
    • 1970-01-01
    • 2011-08-29
    • 2013-03-07
    • 1970-01-01
    • 1970-01-01
    • 2016-06-05
    相关资源
    最近更新 更多