Class: Rack::RESTfulController

Inherits:
Object
  • Object
show all
Defined in:
lib/rack/restful-controller.rb

Defined Under Namespace

Modules: App

Constant Summary collapse

@@collection_methods =
{}
@@member_methods =
{:edit => :get}

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(app, options = {}) ⇒ RESTfulController



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/rack/restful-controller.rb', line 32

def initialize(app, options = {})
  @app = app
  @options = options

  if(options.include?(:collection))
    @@collection_methods.merge!(options[:collection])
  end

  if(options.include?(:member))
    @@member_methods.merge!(options[:member])
  end
end

Class Method Details

.as(klass) ⇒ Object



26
27
28
29
30
# File 'lib/rack/restful-controller.rb', line 26

def self.as(klass)
  a = klass.new
  a.extend(App)
  a
end

Instance Method Details

#call(env) ⇒ Object



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
73
74
75
76
77
78
79
80
81
82
# File 'lib/rack/restful-controller.rb', line 45

def call(env)
  req = Rack::Request.new(env)

  env['restful.params'] = {}

  if req.get? && req.path == '/'
    env['restful.action'] = :index
  elsif req.get? && (match = req.path.match(/^\/(.+?)(?:\/(.+))?$/))
    if(match[2] && @@member_methods[match[2].to_sym] == :get)
      env['restful.action'] = match[2].to_sym
      env['restful.params'] = {'id' => match[1]}
    elsif(match[2] && @@member_methods[match[2].to_sym] != :get)
    elsif(!match[2] && @@collection_methods[match[1].to_sym] == :get)
      env['restful.action'] = match[1].to_sym
    else
      env['restful.action'] = :show
      env['restful.params'] = {'id' => match[1]}
    end
  elsif req.post? && req.path == '/'
    env['restful.action'] = :create
  elsif (req.put? || mimic_put?(req)) && (match = req.path.match(/^\/(.+?)(?:\/(.+))?$/))
    if(match[2] && @@member_methods[match[2].to_sym] == :put)
      env['restful.action'] = match[2].to_sym
      env['restful.params'] = {'id' => match[1]}
    elsif(match[2] && @@member_methods[match[2].to_sym] != :put)
    else
      env['restful.action'] = :update
      env['restful.params'] = {'id' => match[1]}
    end
  elsif (req.delete? || mimic_delete?(req)) && (match = req.path.match(/^\/(.+)$/))
    env['restful.action'] = :destroy
    env['restful.params'] = {'id' => match[1]}
  end

  env['restful.params'].merge!('action' => env['restful.action'].to_s)
  
  @app.call(env)
end

#mimic_delete?(req) ⇒ Boolean



88
89
90
# File 'lib/rack/restful-controller.rb', line 88

def mimic_delete?(req)
  req.post? && req.params['_method'] == 'delete'
end

#mimic_put?(req) ⇒ Boolean



84
85
86
# File 'lib/rack/restful-controller.rb', line 84

def mimic_put?(req)
  req.post? && req.params['_method'] == 'put'
end