Module: Serviceable::ClassMethods

Defined in:
lib/serviceable.rb

Instance Method Summary collapse

Instance Method Details

#acts_as_service(object, options = {}) ⇒ Object

Serviceable Usage

Controller: class PostsController

acts_as_service :post

end



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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/serviceable.rb', line 16

def acts_as_service(object,options={})

  before_filter :assign_new_instance, only: :create
  before_filter :assign_existing_instance, only: [ :show, :update, :destroy ]
  before_filter :assign_collection, only: [ :index, :count ]
  before_filter :did_assign_collection, only: [ :index, :count ]

  define_method("index") do
    respond_to do |format|
      format.json { render json: @collection.to_json(merge_options(options[:index])) }
      format.xml  { render xml: @collection.to_xml(merge_options(options[:index])) }
    end
  end
  
  define_method("count") do
    respond_to do |format|
      format.json { render json: @collection.count }
      format.xml { render xml: @collection.count }
    end
  end

  define_method("create") do
    respond_to do |format|
      if @instance.save
        format.json { render json: @instance }
        format.xml  { render xml: @instance }
      else
        format.json { render json: { errors: @instance.errors.full_messages }, status: :unprocessable_entity }
        format.xml  { render xml: { errors: @instance.errors.full_messages }, status: :unprocessable_entity }
      end
    end
  end

  define_method("show") do
    respond_to do |format|
      format.json { render json: @instance.to_json(merge_options(options[:show])) }
      format.xml  { render xml: @instance.to_xml(merge_options(options[:show])) }
    end
  end

  define_method("update") do
    respond_to do |format|
      if @instance.update_attributes(params[object])
        format.json { head :ok }
        format.xml  { head :ok }
      else
        format.json { render json: { errors: @instance.errors.full_messages }, status: :unprocessable_entity }
        format.xml  { render xml: { errors: @instance.errors.full_messages }, status: :unprocessable_entity }
      end
    end
  end

  define_method("destroy") do
    @instance.destroy

    respond_to do |format|
      format.json { head :no_content }
      format.xml  { head :no_content }
    end
  end

  # query string params can be given in the following formats:
  # only=field1,field2
  # except=field1,field2
  # include=assoc1
  # 
  # if an included association is present, only and except params can be nested
  # include[user][except]=encrypted_password
  # include[user][only][]=first_name&include[user][only][]=last_name
  # include[user][only]=first_name,last_name
  define_method("merge_options") do |options={}|
    merged_options = options || {}
    for key in [:only, :except, :include]
      opts = {key => params[key]} if params[key]
      merged_options = merged_options.merge(opts) if opts
    end
    merged_options = deep_split(merged_options)
    return merged_options
  end
  
  define_method("assign_existing_instance") do
    @instance = object.to_s.camelize.constantize
    if params[:include].kind_of?(Hash)
      @instance = @instance.includes(params[:include].keys)
    end
    if params[:include].kind_of?(String)
      @instance = @instance.includes(params[:include].split(",").map(&:to_sym))
    end
    @instance = @instance.find(params[:id])
  end
  
  define_method("assign_new_instance") do
    @instance = object.to_s.camelize.constantize.new(params[object])
  end
  
  # query string params can be used to filter collections
  #
  # filters apply on associated collections using the following conventions:
  # where[user][category]=Expert
  # where[user][created_at][gt]=20130807T12:34:56.789Z
  #
  # filters can be constructed with AND and OR behavior
  # where[tags][id][in]=123,234,345  (OR)
  # where[tags][id]=123&where[tags][id]=234  (AND)
  define_method("assign_collection") do
    @collection = object.to_s.camelize.constantize.scoped
    if params[:include].kind_of?(Hash)
      for assoc in params[:include].keys
        @collection = @collection.includes(assoc.to_sym)
      end
    end
    if params[:include].kind_of?(String)
      @collection = @collection.includes(params[:include].split(",").map(&:to_sym))
    end
    for assoc in (params[:where].keys rescue [])
      attrs = params[:where][assoc]
      if attrs.kind_of?(Hash)
        for target_column in attrs.keys
          if attrs[target_column].kind_of?(String)
            if is_boolean_column?(target_column)
              value = true if ['t','true','1','y','yes'].include?(attrs[target_column].to_s)
              value = false if ['f','false','0','n','no'].include?(attrs[target_column].to_s)
            else
              value = attrs[target_column]
            end
            @collection = @collection.where(assoc => { target_column => value })
          elsif attrs[target_column].kind_of?(Hash)
            for op in attrs[target_column].keys.map(&:to_sym)
              value = is_time_column?(target_column) ? Time.parse(attrs[target_column][op]) : attrs[target_column][op]
              unless assoc.to_sym==object.to_s.pluralize.to_sym
                @collection = @collection.includes(assoc)
              end
              if op==:gt
                @collection = @collection.where("#{assoc}.#{target_column} > ?",value)
              elsif op==:lt
                @collection = @collection.where("#{assoc}.#{target_column} < ?",value)
              elsif op==:in
                @collection = @collection.where("#{assoc}.#{target_column} IN (?)",value)
              end
            end
          end  
        end
      else
        @collection = @collection.includes(assoc).where(assoc => attrs)
      end
    end
  end
  
  # designed to traverse an entire hash, replacing delimited strings with arrays of symbols
  define_method("deep_split") do |hash={},pivot=','|
    Hash[hash.map {|k,v| [k.to_sym,v.kind_of?(String) ? v.split(pivot).map(&:to_sym) : (v.kind_of?(Hash) ? deep_split(v,pivot) : v)]}]
  end
  
  define_method("is_time_column?") do |column|
    object.to_s.capitalize.constantize.columns.select {|e| e.name==column.to_s}.first.type == :timestamp rescue false
    # !!column[-3,3]=='_at'
  end
  
  define_method("is_boolean_column?") do |column|
    object.to_s.capitalize.constantize.columns.select {|e| e.name==column.to_s}.first.type == :boolean rescue false
  end
end