Module: OpenAPI::Route::ClassMethods

Included in:
OpenAPI::Route
Defined in:
lib/openapi/route.rb

Overview

def static

match '/track_coupon/:source/:id' => 'mobile_banner#track_coupon', :as_ => :track_coupon, :defaults => { :format => 'png' }

Instance Method Summary collapse

Instance Method Details

#create_proc(klass, kmethod, urlpath, opts, client = nil) ⇒ Object



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
# File 'lib/openapi/route.rb', line 27

def create_proc(klass, kmethod, urlpath, opts, client=nil)
  proc = Proc.new() do |args={}|
    headers = args[:headers] || {}
    body = args[:body]
    path = args[:path]
    [:body, :path, :headers].each{|k| args.delete(k)}
    if args.key?(:params)
      params = args[:params] || {}
    else
      params = args
    end
    client = OpenAPI::Route.get_client() if client.nil?

    if opts.has_key?(:default)
      opts[:defaults].each do |k,v|
        if !params.has_key?(k)
          params[k] = v
        end
      end
    end

    OpenAPI.logger.debug params

    path = OpenAPI::Route.replace_uri_vars(path || urlpath, params)

    #1. soon.wrap = do_request opts[:body] => postjson
    OpenAPI.logger.debug(path)
    response = client.do_request(opts[:via], path, {params: params, body: body, headers: headers, options: opts[:options] || {}})
    #2. callback
    return klass.send kmethod.to_s.to_sym, response, {params: params, body: body, headers: headers, options: opts[:options] || {}}
  end
  return proc
end

#draw(client = nil, &block) ⇒ Object



78
79
80
81
# File 'lib/openapi/route.rb', line 78

def draw(client=nil, &block)
  @client = client
  class_eval &block
end

#get_clientObject



74
75
76
# File 'lib/openapi/route.rb', line 74

def get_client
  @client ||= OpenAPI::Client
end

#match(path, callback, name, options = {:via => :get}, client = nil) ⇒ Object



61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/openapi/route.rb', line 61

def match(path, callback, name, options={:via => :get}, client=nil)
  klass_name, klass_method = callback.split("#")
  klass_name = klass_name.classify
  klass = Object.const_get(klass_name)
  if client == nil
    client = get_client()
  end
  proc = create_proc(klass, klass_method, path, options , client)
  client.api_methods << name
  client.create_method(name.to_s, proc)
  return true
end

#replace_uri_vars(path, params) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/openapi/route.rb', line 9

def replace_uri_vars(path, params)
  new_path = path.clone()
  parts = path.split("/")
  parts.each do |part|
    if part.start_with?(":")
      key = part[1..-1].to_sym
      if params.has_key?(key)
        new_path.gsub!(Regexp.compile(":" + key.to_s), CGI.escape(params[key].to_s))
        params.delete(key)
      else
        # @todo raise real errors
        raise "Missing params: set '#{part}' to complete '#{path}' request"
      end
    end
  end
  return new_path
end