Ruby括号括号语法在工作...结束时无法正常工作

时间:2018-06-21 14:23:44

标签: ruby whenever

我正在使用this gem。当我使用以下语法时,它可以正常工作:

every :day do
  rake 'billing:daily'
end

但是,当我使用以下语法时,gem给了我语法错误:

every :day { rake 'billing:daily' }

输出:

~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever/job_list.rb:25:in `instance_eval': config/schedule.rb:26: syntax error, unexpected '{', expecting end-of-input (SyntaxError)
every :day { rake 'billing:daily' }
            ^
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever/job_list.rb:25:in `initialize'
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever.rb:12:in `new'
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever.rb:12:in `cron'
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever/command_line.rb:42:in `run'
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/lib/whenever/command_line.rb:6:in `execute'
    from ~/.rbenv/versions/2.4.3/lib/ruby/gems/2.4.0/gems/whenever-0.10.0/bin/whenever:44:in `<top (required)>'
    from ~/.rbenv/versions/2.4.3/bin/whenever:23:in `load'
    from ~/.rbenv/versions/2.4.3/bin/whenever:23:in `<main>'

不是同一件事吗?为什么前者有效,而后者却无效?

2 个答案:

答案 0 :(得分:6)

这是一个解析/优先级问题。大括号尝试绑定到最近的令牌,在这种情况下为:day,但是您希望将其绑定到every()。您必须编写every(:day) { rake 'billing:daily' }才能将其显式绑定到正确的令牌。

答案 1 :(得分:0)

在红宝石2.4.2 was introduced regression中进行块解析。在红宝石2.4.1中,您可以使用:

every :day { rake 'billing:daily' }

在ruby 2.4.2中,如果使用块调用函数参数,则必须将函数参数包装在括号中,否则将得到SyntaxError

every(:day) { rake 'billing:daily' }