class Socket2me::Middleware::AddScriptTag

Public Class Methods

new(app) click to toggle source
# 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

Public Instance Methods

call(env) click to toggle source
  1. look for a text/html response type from parent app.

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

@param [Hash] env about Rack environment and the request @return [String, Hash, Array]

# 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() click to toggle source

@return [String] the outer Javascript tag with WS client script

# 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