Class: Rails::ExtJS::Direct::RemotingProvider

Inherits:
Object
  • Object
show all
Defined in:
lib/rails-extjs-direct/rack/remoting_provider.rb

Overview

begin

require 'json'

rescue LoadError => load_error

raise "Error loading 'json' library. Please type 'sudo gem install json' and try again."

end

Instance Method Summary collapse

Constructor Details

#initialize(app, rpath) ⇒ RemotingProvider

Returns a new instance of RemotingProvider.



8
9
10
11
12
13
14
15
16
# File 'lib/rails-extjs-direct/rack/remoting_provider.rb', line 8

def initialize(app, rpath)
    if app.kind_of?(String)
      @controllers = {}
      @type = app
    else
      @app = app
    end
    @router_path = rpath
end

Instance Method Details

#add_controller(controller_name) ⇒ Object



18
19
20
# File 'lib/rails-extjs-direct/rack/remoting_provider.rb', line 18

def add_controller(controller_name)
  @controllers[controller_name.capitalize] = "#{controller_name.capitalize}Controller".constantize.direct_actions
end

#call(env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/rails-extjs-direct/rack/remoting_provider.rb', line 26

def call(env)
    if env["PATH_INFO"].match("^"+@router_path)
        output = []
        parse(env["action_controller.request.request_parameters"]).each do |req|
          # have to dup the env for each request
          request_env = env.dup

          # pop poorly-named Ext.Direct routing-params off.
          controller = req.delete("action").downcase
          action =  req.delete("method")

          # set env URI and PATH_INFO for each request
          request_env["PATH_INFO"] = "/#{controller}/#{action}"
          request_env["REQUEST_URI"] = "/#{controller}/#{action}"

          # set request params
          request_env["action_controller.request.request_parameters"] = req

          # call the app!
          # TODO Implement begin/rescue to catch XExceptions
          status, headers, response = @app.call(request_env)

          output << response.body
        end
        # join all responses together
        res = output.join(',')

        # [wrap in array] if multiple responses.  Each controller response will have returned json already
        # so we don't want to re-encode.
        res = "[" + res + "]" if output.length > 1

        # return response
        [200, {"Content-Type" => "text/html"}, [res]]
    else
        @app.call(env)
    end
end

#parse(data) ⇒ Object



64
65
66
# File 'lib/rails-extjs-direct/rack/remoting_provider.rb', line 64

def parse(data)
    return (data["_json"]) ? data["_json"] : [data]
end

#renderObject



22
23
24
# File 'lib/rails-extjs-direct/rack/remoting_provider.rb', line 22

def render
  "<script>Ext.Direct.addProvider({type: '#{@type}', url: '#{@router_path}', actions: #{@controllers.to_json}});</script>"
end