Class: TrkDatatables::Base

Inherits:
Object
  • Object
show all
Extended by:
BaseHelpers
Defined in:
lib/trk_datatables/base.rb

Overview

rubocop:todo Metrics/ClassLength

Direct Known Subclasses

ActiveRecord, Neo4j

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from BaseHelpers

form_field_name, order_set, param_set, range_string

Constructor Details

#initialize(view) ⇒ Base

In tests you can use spy(:view, default_proc: false) when you want to initialize without exceptions when view.params is called or @params = ActiveSupport::HashWithIndifferentAccess.new params



19
20
21
22
23
24
25
26
27
28
29
# File 'lib/trk_datatables/base.rb', line 19

def initialize(view)
  @view = view
  @dt_params = DtParams.new view.params
  @column_key_options = ColumnKeyOptions.new columns, global_search_columns, predefined_ranges
  @preferences = Preferences.new preferences_holder, preferences_field, self.class.name

  # if @dt_params.dt_columns.size != @column_key_options.size
  #   raise Error, "dt_columns size of columns is #{@dt_params.dt_columns.size} \
  #   but column_key_options size is #{@column_key_options.size}"
  # end
end

Instance Attribute Details

#column_key_optionsObject

Returns the value of attribute column_key_options.



15
16
17
# File 'lib/trk_datatables/base.rb', line 15

def column_key_options
  @column_key_options
end

Instance Method Details

#additional_data_for_jsonObject



180
181
182
# File 'lib/trk_datatables/base.rb', line 180

def additional_data_for_json
  {}
end

#all_itemsActiveRecord::Relation

Get all items from db

Examples:

def all_items
  Post.joins(:users).published
end

Returns:

  • (ActiveRecord::Relation)

Raises:

  • (NotImplementedError)


38
39
40
# File 'lib/trk_datatables/base.rb', line 38

def all_items
  raise NotImplementedError, "You should implement #{__method__} method"
end

#all_items_countObject

helper for https://github.com/trkin/trk_datatables/issues/9 which you can override to support group query



172
173
174
# File 'lib/trk_datatables/base.rb', line 172

def all_items_count
  all_items.count
end

#as_json(_attr = nil) ⇒ Object

_attr is given by Rails template, prefix, layout... not used



161
162
163
164
165
166
167
168
# File 'lib/trk_datatables/base.rb', line 161

def as_json(_attr = nil)
  @dt_params.as_json(
    all_items_count,
    filtered_items_count,
    rows(ordered_paginated_filtered_items),
    additional_data_for_json
  )
end

#columnsObject

Define columns of a table For simplest version you can notate column_keys as Array of strings When you need customisation of some columns, you need to define Hash of column_key => { column_options }

Examples:

def column
  %w[posts.id posts.status users.name]
end
def columns
  {
    'posts.id': {},
    'posts.status' => { search: false },
    'users.name' => { order: false },
  }
end

Returns:

  • Array of Hash

Raises:

  • (NotImplementedError)


59
60
61
# File 'lib/trk_datatables/base.rb', line 59

def columns
  raise NotImplementedError, "You should implement #{__method__} method #{link_to_rdoc self.class, __method__}"
end

#default_orderObject



125
126
127
# File 'lib/trk_datatables/base.rb', line 125

def default_order
  [[0, :desc]].freeze
end

#default_page_lengthObject



129
130
131
# File 'lib/trk_datatables/base.rb', line 129

def default_page_length
  10
end

#dt_orders_or_default_index_and_directionObject

Returns dt_orders or default as array of index and direction https://datatables.net/reference/option/order

Returns:

  • [ [0, :desc], ]



108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# File 'lib/trk_datatables/base.rb', line 108

def dt_orders_or_default_index_and_direction
  return @dt_orders_or_default if defined? @dt_orders_or_default

  if columns.blank?
    @dt_orders_or_default = []
  elsif @dt_params.dt_orders.present?
    @dt_orders_or_default = @dt_params.dt_orders
    @preferences.set ORDER, @dt_params.dt_orders
  else
    check_value = lambda { |r|
      r.is_a?(Array) && r[0].is_a?(Array) && r[0][0].is_a?(Integer) && r[0][0] < @column_key_options.size
    }
    @dt_orders_or_default = @preferences.get(ORDER, check_value) || default_order
  end
  @dt_orders_or_default
end

#dt_per_page_or_defaultObject



133
134
135
136
137
138
139
140
141
142
143
# File 'lib/trk_datatables/base.rb', line 133

def dt_per_page_or_default
  return @dt_per_page_or_default if defined? @dt_per_page_or_default

  @dt_per_page_or_default =
    if @dt_params.dt_per_page.present?
      @preferences.set PER_PAGE, @dt_params.dt_per_page
      @dt_params.dt_per_page
    else
      @preferences.get(PER_PAGE) || default_page_length
    end
end

#filter_by_columns(_all) ⇒ Object



93
94
95
96
# File 'lib/trk_datatables/base.rb', line 93

def filter_by_columns(_all)
  raise "filter_by_columns_is_defined_in_specific_orm" \
    "\n  Extent from TrkDatatables::ActiveRecord instead of TrkDatatables::Base"
end

#filter_by_search_all(_all) ⇒ Object



89
90
91
# File 'lib/trk_datatables/base.rb', line 89

def filter_by_search_all(_all)
  raise "filter_by_columns_is_defined_in_specific_orm"
end

#filtered_itemsObject



184
185
186
# File 'lib/trk_datatables/base.rb', line 184

def filtered_items
  filter_by_search_all filter_by_columns all_items
end

#filtered_items_countObject



176
177
178
# File 'lib/trk_datatables/base.rb', line 176

def filtered_items_count
  filtered_items.count
end

#global_search_columnsObject

Define columns that are not returned to page but only used as mathing for global search

Examples:

def global_search_columns
  %w[name email].map {|col| "users.#{col}" } + %w[posts.body]
end


69
70
71
# File 'lib/trk_datatables/base.rb', line 69

def global_search_columns
  []
end

#index_by_column_key(column_key) ⇒ Object

We need this method publicly available since we use it for class method param_set



147
148
149
# File 'lib/trk_datatables/base.rb', line 147

def index_by_column_key(column_key)
  @column_key_options.index_by_column_key column_key
end


192
193
194
# File 'lib/trk_datatables/base.rb', line 192

def link_to_rdoc(klass, method)
  "http://localhost:8808/docs/TrkDatatables/#{klass.name}##{method}-instance_method"
end

#order_and_paginate_items(_filtered_items) ⇒ Object



98
99
100
# File 'lib/trk_datatables/base.rb', line 98

def order_and_paginate_items(_filtered_items)
  raise "order_and_paginate_items_is_defined_in_specific_orm"
end

#ordered_paginated_filtered_itemsObject



188
189
190
# File 'lib/trk_datatables/base.rb', line 188

def ordered_paginated_filtered_items
  order_and_paginate_items filter_by_search_all filter_by_columns all_items
end

#param_get(column_key) ⇒ Object

Helper to populate column search from params, used in RenderHtml#thead

Examples:

@datatable.param_get('users.email')


155
156
157
158
# File 'lib/trk_datatables/base.rb', line 155

def param_get(column_key)
  column_index = index_by_column_key column_key
  @dt_params.param_get column_index
end

#predefined_date_rangesObject

rubocop:todo Metrics/AbcSize



230
231
232
233
234
235
236
237
238
# File 'lib/trk_datatables/base.rb', line 230

def predefined_date_ranges # rubocop:todo Metrics/AbcSize
  {
    Today: Time.zone.today..Time.zone.today,
    Yesterday: [Time.zone.today - 1.day, Time.zone.today - 1.day],
    "This Month": Time.zone.today.beginning_of_month...Time.zone.today,
    "Last Month": Time.zone.today.prev_month.beginning_of_month...Time.zone.today.prev_month.end_of_month,
    "This Year": Time.zone.today.beginning_of_year...Time.zone.today
  }
end

#predefined_datetime_rangesObject

rubocop:todo Metrics/AbcSize



240
241
242
243
244
245
246
247
248
249
# File 'lib/trk_datatables/base.rb', line 240

def predefined_datetime_ranges # rubocop:todo Metrics/AbcSize
  {
    Today: Time.zone.now.beginning_of_day..Time.zone.now.end_of_day,
    Yesterday: [Time.zone.now.beginning_of_day - 1.day, Time.zone.now.end_of_day - 1.day],
    "This Month": Time.zone.today.beginning_of_month.beginning_of_day...Time.zone.now.end_of_day,
    "Last Month":
      Time.zone.today.prev_month.beginning_of_month.beginning_of_day...Time.zone.today.prev_month.end_of_month.end_of_day,
    "This Year": Time.zone.today.beginning_of_year.beginning_of_day...Time.zone.today.end_of_day
  }
end

#predefined_rangesObject



222
223
224
225
226
227
228
# File 'lib/trk_datatables/base.rb', line 222

def predefined_ranges
  Time.zone ||= "UTC"
  {
    date: predefined_date_ranges,
    datetime: predefined_datetime_ranges
  }
end

#preferences_fieldObject

Override if you use different than :preferences You can generate with this command:



218
219
220
# File 'lib/trk_datatables/base.rb', line 218

def preferences_field
  :preferences
end

#preferences_holderObject

Override this to set model where you can store order, index, page length

Examples:

def preferences_holder
  @view.current_user
end


210
211
212
# File 'lib/trk_datatables/base.rb', line 210

def preferences_holder
  nil
end

#render_html(search_link = nil, html_options = {}) ⇒ Object



196
197
198
199
200
201
202
203
# File 'lib/trk_datatables/base.rb', line 196

def render_html(search_link = nil, html_options = {})
  if search_link.is_a? Hash
    html_options = search_link
    search_link = nil
  end
  render = RenderHtml.new(search_link, self, html_options)
  render.result
end

#rows(_page_items) ⇒ Object

Define page data

Examples:

def rows(page_items)
  page_items.map do |post|
  post_status = @view. :span, post.status, class: "label label-#{@view.convert_status_to_class post.status}"
    [
      post.id,
      post_status,
      @view.link_to(post.user.name, post.user)
    ]
  end
end

Raises:

  • (NotImplementedError)


85
86
87
# File 'lib/trk_datatables/base.rb', line 85

def rows(_page_items)
  raise NotImplementedError, "You should implement #{__method__} method"
end