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.
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_tag ⇒ String
Returns 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 |