Class: DDC::ServiceBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/ddc/service_builder.rb

Class Method Summary collapse

Class Method Details

.build(model_type) ⇒ Object



3
4
5
6
7
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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/ddc/service_builder.rb', line 3

def self.build(model_type)
  Class.new do
    include DDC::ResponseBuilder
    class << self
      attr_accessor :model_type, :ar_model, :finder
    end

    @model_type = model_type
    ar_class_name = model_type.to_s.camelize
    @ar_model = Object.const_get(ar_class_name)

    @finder = nil
    begin
      @finder = Object.const_get("#{ar_class_name}Finder")
    rescue NameError
      # we use the AR Model as a fallback 
    end

    def find(context)
      id = context[:id]
      me = custom_finder ? custom_finder.find(context) : 
                           ar_model.where(id: id)
      if me.present?
        ok(me)
      else
        not_found
      end
    end

    def find_all(context={})
      mes = custom_finder ? custom_finder.find_all(context) : 
                            ar_model.all
      ok(mes)
    end

    def update(context)
      id, updates = context.values_at :id, self.class.model_type
      me = self.class.ar_model.where id: id

      if me.present?
        success = me.update_attributes translated_updates
        if success
          ok(me)
        else
          not_valid(me)
        end
      else
        not_found
      end
    end

    def create(context)
      attributes = context.values_at self.class.model_type
      me = self.class.ar_model.create attributes
      if me.persisted?
        created(me)
      else
        not_valid(me)
      end
    end

    def delete(context)
      id = context[:id]
      me = custom_finder ? custom_finder.find(context) : 
                           ar_model.where(id: id)
      if me.present?
        me.destroy
        deleted
      else
        not_found
      end
    end

    private
    def custom_finder
      self.class.finder
    end

    def ar_model
      self.class.ar_model
    end

  end
end