Module: ActiveRecordApiWrapper::ClassMethods

Defined in:
lib/ar_http_wrapper/active_record_api_wrapper.rb

Instance Method Summary collapse

Instance Method Details

#api(api_class) ⇒ Object



8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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
63
64
# File 'lib/ar_http_wrapper/active_record_api_wrapper.rb', line 8

def api(api_class)
  klass = self
  resources_name = klass.to_s.underscore.pluralize
  klass_to_param_key = klass.klass_to_param_key

  api_class.resource :"#{resources_name}" do
    api_class.desc "Builds a record."
    api_class.get "/new" do
      klass.new
    end

    api_class.desc "Creates a record."
    api_class.params do
      requires klass_to_param_key, :desc => "The new record attributes."
    end
    api_class.post "/" do
      klass.create(params[klass_to_param_key])
    end

    api_class.desc "Updates a record."
    api_class.params do
      requires :id, :desc => "The record id."
      requires klass_to_param_key, :desc => "The updated record attributes."
    end
    api_class.put "/:id" do
      updated_attr = params[klass_to_param_key]
      instance = klass.find_by_id(params[:id])
      instance.try(:update_attributes,updated_attr)
    end

    api_class.desc "Shows a record."
    api_class.params do
      requires :id, :desc => "The record id."
    end
    api_class.get "/:id" do
      klass.find_by_id(params[:id])
    end

    api_class.desc "Destroys a record."
    api_class.params do
      requires :id, :desc => "The record id."
    end
    api_class.delete "/:id" do
      instance = klass.find_by_id(params[:id])
      instance.try(:destroy)
    end

    api_class.desc "Collects records."
    api_class.get "/" do
      conditions = params[:conditions]
      offset = params[:offset]
      limit = params[:limit]
      records = klass.find(:all, :conditions => conditions, :offset => offset, :limit => limit)
      params[:count] ? records.count : records
    end
  end
end

#klass_to_param_keyObject



5
6
7
# File 'lib/ar_http_wrapper/active_record_api_wrapper.rb', line 5

def klass_to_param_key
  self.to_s.underscore.split('/').last.to_sym
end