我尝试按照以下链接将网络套接字集成到我的Rails应用程序中:https://github.com/websocket-rails/websocket-rails/wiki/Installation-and-Setup
我使用Ruby 2.0和Rails3。 相关文件的内容:
的Gemfile:
gem 'websocket-rails
events.rb
WebsocketRails::EventMap.describe do
subscribe :awesomeness_approval, :to => ChatController, :with_method => :awesomeness_approval
end
development.rb
... config.middleware.delete Rack :: Lock ...
chat_controller.rb
class ChatController < WebsocketRails::BaseController
def initialize_session
# perform application setup here
controller_store[:message_count] = 0
end
def awesomeness_approval
if message[:awesomeness] > 5
trigger_success {:m => 'awesome level is sufficient'}
else
trigger_failure {:m => 'awesome level is insufficient'}
end
end
end
chat.js
var dispatcher = new WebSocketRails('localhost:3000/websocket');
dispatcher.on_open = function(data) {
console.log('Connection has been established: ', data);
}
var success = function(response) {
console.log("You are awesome because: "+response.message);
}
var failure = function(response) {
console.log("You are not very awesome because: "+response.message);
}
var message = { awesomeness: 4 }
dispatcher.trigger('awesomeness_approval', message, success, failure);
当我尝试启动rails服务器时,出现以下错误:
w/app/controllers/chat_controller.rb:9: syntax error, unexpected =>, expecting '}' (SyntaxError)
trigger_success {:m => 'awesome level is sufficient'}
...
/app/controllers/chat_controller.rb:11: syntax error, unexpected =>, expecting '}'
trigger_failure {:m => 'awesome level is insufficient'}
但是,如果我注释掉上述内容,我就可以启动服务器,并且浏览器可以连接到Web套接字。在浏览器控制台上可以看到以下输出:
"Connection has been established: " Object { connection_id: "f66c4298eb103312e181" } chat.js:3
请帮忙。
答案 0 :(得分:1)
您的错误来自方法调用中的语法歧义。
写作时
trigger_success {:m => 'awesome level is sufficient'}
开口大括号被解释为该方法的块参数的开始。但是,您打算将它作为哈希。解释为一个块,它确实是错误的语法,因为一个块不允许一个简单的哈希火箭。
您可以解决这种歧义,您可以使用括号:
trigger_success({:m => 'awesome level is sufficient'})
这样一来,ruby解析器很明显你实际上是指将一个hash参数传递给方法并且当前正在解析。