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.



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

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])


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

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

  return response unless headers['Content-Type'].include?('text/html')

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

  [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



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

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