Class: Socket2me::Middleware::AddScriptTag

Inherits:
Object
  • Object
show all
Defined in:
lib/socket2me/middleware/add_script_tag.rb

Instance Method Summary collapse

Constructor Details

#initialize(app) ⇒ AddScriptTag

Returns a new instance of AddScriptTag.



7
8
9
10
# File 'lib/socket2me/middleware/add_script_tag.rb', line 7

def initialize(app)
  @app = app
  @ws_url = "ws://#{Socket2me.config.ws_host}:#{Socket2me.config.ws_port}"
end

Instance Method Details

#call(env) ⇒ String, ...

  1. look for a text/html response type from parent app.

  2. replace the closing ‘</body>` with the WebSocket client code.

Parameters:

  • env (Hash)

    about Rack environment and the request

Returns:

  • (String, Hash, Array[String])


17
18
19
20
21
22
23
24
25
26
27
# File 'lib/socket2me/middleware/add_script_tag.rb', line 17

def call(env)
  response = @app.call(env)
  status, headers, body = *response

  return response unless headers['Content-Type'] == 'text/html'

  # replace the last body with script
  new_body = body.join.gsub(%r{(</body>)}i,"#{script_tag}\\1")

  return status, headers, [new_body]
end

#script_tagString

Returns the outer Javascript tag with WS client script.

Returns:

  • (String)

    the outer Javascript tag with WS client script



30
31
32
33
34
35
36
37
38
39
40
# File 'lib/socket2me/middleware/add_script_tag.rb', line 30

def script_tag
  <<-HTML
<script>
(function (ws) {
    ws.onmessage = function (msg) {
new Function(msg.data)();
    }
})(new WebSocket("#{@ws_url}"));
</script>
  HTML
end