1

我第一次深入研究 Ruby 和 Sinatra,并浏览了 Alan Harris 和 Konstatin Haase 的“ Sinatra Up and Running ”。在整理了我的 Ruby 版本(使用 RVM)之后,在创建扩展时,我直到第 3 章都没有遇到任何问题。代码如下(post_get.rb):

require 'sinatra/base'

module Sinatra
  module PostGet
    def post_get (route, &block)
      get (route, &block)
      post (route, &block)
    end
  end

  register PostGet
end

与 (post_get_test.rb) 一起使用:

require 'sinatra'
require './post_get'

post_get '/' do
        "Hello #{params[:names]}"
end

但是,每当我运行“ruby post_get_test.rb”时,我都会立即收到以下运行时错误:

user@UbuntuOne:~/sinatra$ ruby post_get_test.rb 
/home/user/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require': /home/user/sinatra/post_get.rb:6: syntax error, unexpected ',', expecting ')' (SyntaxError)
      get (route, &block)
                 ^
/home/user/sinatra/post_get.rb:7: syntax error, unexpected ',', expecting ')'
      post (route, &block)
                  ^
/home/user/sinatra/post_get.rb:13: syntax error, unexpected $end, expecting keyword_end
    from /home/user/.rvm/rubies/ruby-1.9.2-p320/lib/ruby/site_ruby/1.9.1/rubygems/custom_require.rb:36:in `require'
    from post_get_test.rb:2:in `<main>'

我什至不确定从哪里开始解决这个问题。有人可以指出我正确的方向来解决这个问题吗?

谢谢。

4

1 回答 1

2

您发布的代码是正确的,但与错误消息中报告的代码不同。

In the error message the lines causing the error look like this:

get (route, &block)

and

post (route, &block)

Note the space between the get or post and the opening (. In Ruby when you call a method and you use parenthesis there mustn’t be a space between the method name and the opening parenthesis (like the code block in your question).

Make sure in your actual code there isn’t a space at this point and you should be okay.

What’s happening is Ruby is trying to parse what is contained in the parenthesis and pass the result as the only argument to the method, rather than using the contents of them as the list of arguments.

于 2013-04-07T22:36:00.260 回答