The readme for faye-websocket-ruby
has the below example. What does the line of code
p [:close, event.code, event.reason]
do and what does p
mean there? Also what does ws.rack_response
do and why is it necessary?
# app.rb
require 'faye/websocket'
App = lambda do |env|
if Faye::WebSocket.websocket?(env)
ws = Faye::WebSocket.new(env)
ws.on :message do |event|
ws.send(event.data)
end
ws.on :close do |event|
p [:close, event.code, event.reason]
ws = nil
end
# Return async Rack response
ws.rack_response
else
# Normal HTTP request
[200, {'Content-Type' => 'text/plain'}, ['Hello']]
end
end
p()
is an instance method of the Kernel
class see here. It is used for printing (like puts
does) but it calls the inspect
method on the argument. It is useful for debugging because you can see exactly what the value is because with puts the integer 1 will be printed as "1"
which is not what it is.
Every Rack application must respond to a method called call
that accepts the environment env
and returns an array of the form
[http_code, headers, body]
On the example above you can see that the App
object is a lambda
accepting the env
and returning an array of the aforementioned form. Thus it is a Rack application given that a lambda
has a method call
.
The rack_response
method does nothing more than returning a rack compatible array as you can see HERE.
More about Rack applications HERE.