Class: Socket2me::Middleware::AddScriptTag
- Inherits:
-
Object
- Object
- Socket2me::Middleware::AddScriptTag
- Defined in:
- lib/socket2me/middleware/add_script_tag.rb
Instance Method Summary collapse
-
#call(env) ⇒ String, ...
1.
-
#initialize(app) ⇒ AddScriptTag
constructor
A new instance of AddScriptTag.
-
#script_tag ⇒ String
The outer Javascript tag with WS client script.
Constructor Details
Instance Method Details
#call(env) ⇒ String, ...
-
look for a text/html response type from parent app.
-
replace the closing ‘</body>` with the WebSocket client code.
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_tag ⇒ String
Returns 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 |