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.
-
#js_erb ⇒ String
Adjust the javascript client code as needed.
-
#script_tag ⇒ String
The outer Javascript tag with WS client script.
Constructor Details
#initialize(app) ⇒ AddScriptTag
Returns a new instance of AddScriptTag.
9 10 11 12 |
# File 'lib/socket2me/middleware/add_script_tag.rb', line 9 def initialize(app) @app = app @ws_url = "ws://#{Socket2me.config.ws_host}:#{Socket2me.config.ws_port}" end |
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.
19 20 21 22 23 24 25 26 27 28 29 30 31 |
# File 'lib/socket2me/middleware/add_script_tag.rb', line 19 def call(env) response = @app.call(env) status, headers, body = *response return response unless headers['Content-Type'] == 'text/html' full_body = body.join # replace the last body with script full_body.gsub!(%r{(</body>)}i,"#{script_tag}\\1") return status, headers, [full_body] end |
#js_erb ⇒ String
Adjust the javascript client code as needed.
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 |
# File 'lib/socket2me/middleware/add_script_tag.rb', line 41 def js_erb "(function () {\n var socket = new WebSocket(\"<%= @ws_url %>\");\n\n function log(message) {\n console.log.apply(console, arguments);\n }\n\n try {\n socket.onopen = function () {\n log(\"Socket Status: \" + socket.readyState + \" (open)\");\n };\n\n socket.onclose = function () {\n log(\"Socket Status: \" + socket.readyState + \" (closed)\");\n };\n\n socket.onmessage = function (msg) {\n try {\n // execute in an anonymous function\n new Function(msg.data)();\n } catch (msgEx){\n console.error(\"Could not execute `%s` due to %o\", msg.data, msgEx);\n }\n }\n } catch (exception) {\n console.error(\"Error: \" + exception);\n }\n})();\n JS\nend\n" |
#script_tag ⇒ String
Returns the outer Javascript tag with WS client script.
34 35 36 37 |
# File 'lib/socket2me/middleware/add_script_tag.rb', line 34 def script_tag js = ERB.new(js_erb).result(binding) "<script>#{js}</script>" end |