Module: Apiary::ClassMethods

Defined in:
lib/apiary.rb

Instance Method Summary collapse

Instance Method Details

#__as_app(&blk) ⇒ Object



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
# File 'lib/apiary.rb', line 55

def __as_app(&blk)
  router = HttpRouter.new
  @cmds.each do |cmd|
    path = "#{@version}/#{cmd.path || default_path(cmd.method)}".squeeze('/')
    route = router.add(path)
    route.send(cmd.http_method) if cmd.http_method
    route.to { |env|
      instance = (blk ? blk.call : new)
      instance.rack_env = env
      response = AsyncResponse.new(env)
      if cmd.async?
        instance.async_response = response
        instance.send(cmd.method, *env['router.response'].param_values)
      else
        EM.defer(proc{
          response.status = 200
          response << instance.send(cmd.method, *env['router.response'].param_values).to_s
        }, proc{
          response.done
        })
      end
      response.finish
    }
  end
  router
end

#__set_routing(method, path, async = false) ⇒ Object



32
33
34
# File 'lib/apiary.rb', line 32

def __set_routing(method, path, async = false)
  @http_method, @path, @async = method, path, async
end

#default_path(m) ⇒ Object



45
46
47
48
49
50
51
52
53
# File 'lib/apiary.rb', line 45

def default_path(m)
  instance_method(m).parameters_extra.inject(m.to_s) do |path, arg|
    path << case arg.type
    when :required then "/:#{arg.name}"
    when :optional then "/(:#{arg.name})"
    when :splat    then "/*#{arg.name}"
    end
  end
end

#method_added(m) ⇒ Object



36
37
38
39
40
41
42
43
# File 'lib/apiary.rb', line 36

def method_added(m)
  if @http_method
    ParametersExtra.register(Callsite.parse(caller.first).filename)
    @cmds ||= []
    @cmds << ApiMethod.new(m, @http_method, @path, @async)
    @http_method, @path, @async = nil, nil, nil
  end
end

#run(port = 3000, &blk) ⇒ Object



82
83
84
85
86
87
88
# File 'lib/apiary.rb', line 82

def run(port = 3000, &blk)
  api = self
  raise "No version specified" unless @version
  Thin::Server.new('0.0.0.0', port) {
    run api.__as_app(&blk)
  }.start
end

#version(number) ⇒ Object



28
29
30
# File 'lib/apiary.rb', line 28

def version(number)
  @version = number
end