Module: Datatable

Defined in:
lib/datatablesnet/datatable.rb

Defined Under Namespace

Classes: UrlHelper

Class Method Summary collapse

Class Method Details

.build_condition(klass, params = {}, options = {}) ⇒ Object



267
268
269
270
# File 'lib/datatablesnet/datatable.rb', line 267

def build_condition(klass, params={}, options = {})
  grid_options = parse_params klass, params
  build_condition_internal(klass, grid_options, options[:conditions].present? ? options[:conditions] : nil)
end

.build_condition_internal(klass, grid_options, conditions) ⇒ Object



272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
# File 'lib/datatablesnet/datatable.rb', line 272

def build_condition_internal(klass, grid_options, conditions)
  field_filter_where = {}
  all_filter_where = {}
  search_filter_where = {}

  grid_options[:filter_by].each do |column, value|
    field_filter_where[column] = value
  end

  # Search all searchable columns
  if grid_options[:search].present?
    grid_options[:columns].each do |column|
      if column[:searchable].to_b
        all_filter_where[column[:field]] = grid_options[:search]
      end
    end
  end

  #process search_by
  grid_options[:search_by].each do |column, value|
    if value.instance_of?(Hash)
      if value[:to].present?
        search_filter_where[column] = (value[:from]..value[:to])
      else
        search_filter_where[column] = value[:from]
      end
    else
      search_filter_where[column] = value
    end
  end

  if !field_filter_where.empty? or !all_filter_where.empty? or !search_filter_where.empty?
    sql_where = [field_filter_where.sql_like, all_filter_where.sql_or.sql_like, search_filter_where.sql_and].sql_and.sql_where
    if conditions
      if conditions.instance_of?(Array)
        condition_string = conditions[0]
        condition_params = conditions[1..-1]
      else
        condition_string = conditions
        condition_params = []
      end
      condition_string << " and (" << sql_where[0] << ")"
      condition_params += sql_where[1..-1]
      conditions = [condition_string] + condition_params
    else
      conditions = sql_where
    end
  end
  conditions
end

.build_row_meta(row, grid_options) ⇒ Object



377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
# File 'lib/datatablesnet/datatable.rb', line 377

def build_row_meta row, grid_options
  url_helper = UrlHelper.new
  meta={}
  meta[:urls] = {}
  grid_options[:columns].each do |column|
    if column[:view_link].present?
      view_link = column[:view_link]
      if view_link == "."
        url = url_helper.url_for(row)
      else
        link_obj = row.send(view_link)
        if link_obj
          url = url_helper.url_for(link_obj)
        else
          url = nil
        end
      end
      meta[:urls][column[:field]] = url
    end
  end
  return meta
end

.convert_param(klass, field_name, value) ⇒ Object



256
257
258
259
260
261
262
263
264
# File 'lib/datatablesnet/datatable.rb', line 256

def convert_param klass, field_name, value
  case klass.columns_hash[field_name].type
    when :date, :datetime
      value = Date.parse(value)
    when :integer, :float, :decimal
      value = value.to_i
  end
  value
end

.datatable_get_column_data(row, column) ⇒ Object



175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
# File 'lib/datatablesnet/datatable.rb', line 175

def datatable_get_column_data row, column
  obj = get_field_data(row, column[:field])

  if column[:view_link].present?
    if column[:view_link] == "."
      return link_to(obj, row)
    else
      link_obj = row.send(column[:view_link])
      if link_obj
        return link_to(obj, link_obj)
      else
        return obj
      end
    end
  else
    return obj
  end
end

.datatable_get_column_defs(options, columns) ⇒ Object



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
# File 'lib/datatablesnet/datatable.rb', line 118

def datatable_get_column_defs options, columns
  column_defs = []
  column_options_map = {:width => "sWidth",
                        :sortable => "bSortable",
                        :searchable => "bSearchable",
                        :class => "sClass"}


  column_index =0
  columns.each do |column|
    column_options = {}
    column_options_map.each do |k,v|
      if column[k].present?
        column_options[v] = column[k] unless k==:width and request.env['HTTP_USER_AGENT'] =~ /Firefox/
      end
    end
    column_options["fnRender"] = NoEscape.new(options[:render]) if column[:render].present?
    column_options["fnRender"] = NoEscape.new("function (obj) {return #{column[:format]}(obj.aData[#{column_index}])}") if column[:format].present?
    if column[:view_link].present? and options[:server_side]
      column_options["fnRender"] = NoEscape.new("function (obj) {if(obj.aData[#{columns.length}]['urls']['#{column[:field]}']!=null) {return '<a href = ' + obj.aData[#{columns.length}]['urls']['#{column[:field]}'] + '>' + obj.aData[#{column_index}] + '</a>'} else {return obj.aData[#{column_index}]} }")
    end

    unless column_options.empty?
      column_defs << column_options
    else
      column_defs << nil
    end
    column_index+=1
  end

  if options[:show_actions]
    column_defs << nil
  end

  if options[:server_side]
    if request.env['HTTP_USER_AGENT'] =~ /Firefox/
      column_defs << {"sClass" => "hidden"}
    else
      column_defs << {"bVisible" => false}
    end
  end

  return column_defs
end

.datatable_tag(id, columns = [], rows = nil, options = {}) ⇒ Object



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
# File 'lib/datatablesnet/datatable.rb', line 54

def datatable_tag id, columns = [], rows = nil, options = {}
  options_map = {:sort_by => "aaSorting",
                 :search => "bFilter",
                 :search_label => "sSearch",
                 :processing => "bProcessing",
                 :persist_state => "bSaveState",
                 :per_page => "iDisplayLength",
                 :no_records_message => "sZeroRecords",
                 :auto_width => "bAutoWidth",
                 :dom => "sDom",
                 :data_url => "sAjaxSource",
                 :server_side => "bServerSide",
                 :auto_scroll => "bScrollInfinite",
                 :pagination_type => "sPaginationType",
                 :paginate => "bPaginate",
                 :save_state => "bStateSave"
                 }


  options =
    {
      :show_actions       => false,
      :per_page           => 25,
      :toolbar_external   => false
    }.merge(options)

  url = URI::split(options[:data_url]);

  index = 0
  columns.each do |column|
    column[:label] = field_to_label(column[:field]) unless column[:label].present?
    if options[:data_url].present?
      options[:data_url] << "?" if column == columns.first and url[7] == nil
      options[:data_url] << "&" if column == columns.first and url[7] != nil
      options[:data_url] << "column_field_#{index.to_s}=#{column[:field]}"
      if column[:view_link].present?
        options[:data_url] << "&column_view_link_#{index.to_s}=#{column[:view_link]}"
      end
      options[:data_url] << "&" unless column == columns.last
    end
    index += 1
  end

  if options[:toolbar].present? or options[:toolbar_external]
    options[:dom]='<"toolbar">lfrtip'
  end

  table_options = {}
  options_map.each do |k,v|
    if options[k].present?
      table_options[v] = options[k]
    end
  end

  table_options["fnInfoCallback"] = NoEscape.new(options[:info_callback]) if options[:info_callback].present?

  table_options["aoColumns"] = datatable_get_column_defs(options,columns)

  config = {:options => options, :columns =>columns, :table_options => table_options}
  config.to_json
  
  render :partial => "datatablesnet/table", :locals => { :table_id => id, :columns => columns, :rows => rows, :config => config}
end

.field_to_label(field) ⇒ Object



194
195
196
197
# File 'lib/datatablesnet/datatable.rb', line 194

def field_to_label(field)
  label = field.gsub(/[_.]/, " ")
  label.to_s.gsub(/\b\w/){$&.upcase}
end

.find(klass, params = {}, options = {}) ⇒ Object



323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
# File 'lib/datatablesnet/datatable.rb', line 323

def find(klass, params={}, options = {})
  puts params.to_json

  grid_options = parse_params klass, params

  options[:page] = grid_options[:page]
  options[:per_page] = grid_options[:per_page]

  # Build order by
  grid_options[:order_by].each do |column, order|
    if column
      if options[:order].present?
        options[:order] << ", "
      else
        options[:order] = ""
      end
      options[:order] << "#{column} #{order}"
    end
  end

  # Build filter by
  options[:conditions] = build_condition_internal(klass, grid_options, options[:conditions].present? ? options[:conditions] : nil)

  puts options[:conditions]

  rows = klass.paginate options

  objects = []
  rows.each do |row|
    object = []
    grid_options[:columns].each do |column|
      object << get_field_data(row, column[:field])
    end

    meta = build_row_meta row, grid_options
    object << meta
    objects << object
  end

  total_records = klass.count
  if options[:conditions].present?
    total_display_records = klass.count(:conditions => options[:conditions])
  else
    total_display_records = total_records
  end
  json_data = {:sEcho => params[:sEcho],
               :iTotalRecords =>  total_records,
               :iTotalDisplayRecords => total_display_records,
               :aaData => objects
  }
  return json_data
end

.get_field_data(obj, field) ⇒ Object



163
164
165
166
167
168
169
170
171
172
173
# File 'lib/datatablesnet/datatable.rb', line 163

def get_field_data obj, field
  attrs = field.split('.')
  attrs.each do |attr|
    if obj
      obj = obj.send attr
    else
      return ""
    end
  end
  return obj
end

.parse_params(klass, params) ⇒ Object



199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
# File 'lib/datatablesnet/datatable.rb', line 199

def parse_params klass, params
  grid_options = {}
  columns = []
  order_by = {}
  filter_by = {}
  (0..params[:iColumns].to_i-2).each do |index|
    column = {}
    column[:field] = params["column_field_#{index}"]
    column[:searchable] = params["bSearchable_#{index}"].to_b
    column[:sortable] = params["bSortable_#{index}"].to_b
    column[:index] = index
    if params["column_view_link_#{index}"].present?
      column[:view_link] = params["column_view_link_#{index}"]
    end
    columns << column
    if params["iSortCol_#{index}"].present?
      order_column_index = params["iSortCol_#{index}"]
      order_column = params["column_field_#{order_column_index}"]
      order_column_order = params["sSortDir_#{index}"] || "DESC"
      order_by[order_column] = order_column_order
    end
    if params["sSearch_#{index}"].present?
      filter_by[column[:field]] = params["sSearch_#{index}"]
    end
  end

  search_by = {}
  params.each do |key, value|
    if key =~ /query_.*/ and !value.empty?
      if key =~ /.*_to/
        field_name = key[6..-4]
        search_by[field_name] = {} unless search_by[field_name].present?
        search_by[field_name][:to] = convert_param(klass, field_name, value)
      elsif key =~ /.*_from/
        field_name = key[6..-6]
        search_by[field_name] = {} unless search_by[field_name].present?
        search_by[field_name][:from] = convert_param(klass, field_name,value)
      else
        field_name = key[6..-1]
        search_by[field_name] = convert_param(klass, field_name, value)
      end
    end
  end

  grid_options[:search_by] = search_by
  grid_options[:columns] = columns
  grid_options[:order_by] = order_by
  grid_options[:filter_by] = filter_by
  grid_options[:page] = (params[:iDisplayStart].to_i/params[:iDisplayLength].to_i rescue 0)+1
  grid_options[:per_page] = params[:iDisplayLength]
  if params["sSearch"].present?
    grid_options[:search] = params["sSearch"]
  end

  grid_options
end

.template_pathObject



48
49
50
51
52
# File 'lib/datatablesnet/datatable.rb', line 48

def template_path
  path = File.expand_path('..', __FILE__)
  $:.unshift(path)
  path
end