Class: CmseditController

Inherits:
DcApplicationController show all
Defined in:
app/controllers/cmsedit_controller.rb

Overview

This is main controller for processing actions by DRG forms. It provides CRUD actions for editing MongoDB documents. DRG CMS does not require controller to be made for every document model but centers all actions into single controller. Logic required to control data entry is provided within DRG forms which are loaded dynamically for every action.

Most of data entry controls must therefore be done in document models definitions. And there are controls that cannot be done in document models. Like controls which include url parameters or accessing session variables. This is hard to be done in model therefore cmsedit_controls had to be invented. cmsedit_controls are modules with methods that are injected into cmsedit_controller and act in runtime like they are part of cmsedit_controller.

Since Ruby and Rails provide some automagic loading of modules DRG CMS controls must be saved into app/controllers/drgcms_controls folder. Every model can have its own controls file. dc_page model’s controls live in dc_page_controls.rb file. If model has embedded document its control’s would be found in model_embedded_controls.rb. By convention module names are declared in camel case, so our dc_page_controls.rb declares DrgcmsControls::DcPageControls module.

Controls (among other) may contain 6 fixed callback methods. These methods are:

  • dc_new_record

  • dc_before_edit

  • dc_before_save

  • dc_after_save

  • dc_before_delete

  • dc_after_delete

Methods dc_before_edit, before_save or before_delete may also effect flow of the application. If method return false (not nil but FalseClass) normal flow of the program is interrupted and last operation is canceled.

Second control methods that can be declared in DRG CMS controls are filters for viewing and sorting documents. It is often required that dynamic filters are applied to result_set documents.

result_set:
  filter: current_users_documents

Example implemented controls method:

def current_users_documents
  if dc_user_can(DcPermission::CAN_READ)
    dc_page.where(created_by: session[:user_id])
  else
    flash[:error] = 'You can not perform this operation!'
    nil
  end
end

If filter method returns false user will be presented with flash error.

Instance Method Summary collapse

Methods inherited from DcApplicationController

#dc_dump, #dc_edit_mode?, #dc_find_form_file, #dc_get_site, #dc_log_visit, #dc_render_404, #dc_user_has_role, #set_page_title

Instance Method Details

#check_filter_optionsObject

Will check and set current filter options for result set. Subroutine of index method.



173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'app/controllers/cmsedit_controller.rb', line 173

def check_filter_options() #:nodoc:
  table_name = @tables.first[1]
  model      = @tables.first[0]
  session[table_name] ||= {}
# process page
  session[table_name][:page] = params[:page] if params[:page]
# new filter is applied
  if params[:filter]
    set_session_filter(table_name)
    session[table_name][:page] = 1
  end
# if data model has field dc_site_id ensure that only documents which belong to the site are selected.
  site_id = dc_get_site._id if dc_get_site
# dont't filter site if no dc_site_id field or user is ADMIN
  site_id = nil if !model.method_defined?('dc_site_id') or dc_user_can(DcPermission::CAN_ADMIN)
  site_id = nil if session[table_name][:filter].to_s.match('dc_site_id')
#  
  if @records = DcFilter.get_filter(session[table_name][:filter])
    @records = @records.and(dc_site_id: site_id) if site_id
  else
    @records = if site_id
      model.where(dc_site_id: site_id)
    else
      model
    end
  end
=begin  
# TODO Use only fields requested. Higly experimental but necessary in some scenarios
  if (columns = @form['result_set']['columns'])
    cols = []
    columns.each { |k,v| cols << v['name'] }
    p '*',cols,'*'
    @records = @records.only(cols)
  end
=end  
# pagination if required
  per_page = (@form['result_set']['per_page'] || 30).to_i
  if per_page > 0
    @records = @records.page(session[table_name][:page]).per(per_page)
  end
end

#check_sort_optionsObject

Will check and set sorting options for current result set. Subroutine of index method.



87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
# File 'app/controllers/cmsedit_controller.rb', line 87

def check_sort_options() #:nodoc:
  table_name = @tables.first[1]
  old_sort = session[table_name][:sort].to_s
  sort, direction = old_sort.split(' ')
# sort is requested
  if params['sort']
    # reverse sort if same selected
    if params['sort'] == sort
      direction = (direction == '1') ? '-1' : '1'
    end
    direction ||= 1
    sort = params[:sort]
    session[table_name][:sort] = "#{params['sort']} #{direction}"
    session[table_name][:page] = 1
  end
  @records.sort( sort => direction.to_i ) if session[table_name][:sort]
  params['sort'] = nil # otherwise there is problem with other links
end

#createObject

Create (or duplicate) action. Action is also used for turning filter on.



397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
# File 'app/controllers/cmsedit_controller.rb', line 397

def create
# abusing create for turning filter on
  return index if params[:filter].to_s == 'on'
# not authorized
  unless dc_user_can(DcPermission::CAN_CREATE)
    flash[:error] = t('drgcms.not_authorized')
    return index
  end
#
  if params['id'].nil? # create record
# Prevent double form submit
    params[:form_time_stamp] = params[:form_time_stamp].to_i
    session[:form_time_stamp] ||= 0
    return index if params[:form_time_stamp] <= session[:form_time_stamp]
    session[:form_time_stamp] = params[:form_time_stamp]
#    
    create_new_empty_record
    params[:return_to] = 'index' if params[:commit] == t('drgcms.save&back') # save & back
    if save_data
      flash[:info]    = t('drgcms.doc_saved')
      return process_return_to(params[:return_to]) if params[:return_to]
      
      @parms['id']     = @record.id     # must be set, for proper update link
      params[:id]      = @record.id     # must be set, for find_record
      edit
      #      render action: :edit
    else # error
      render action: :new
    end
  else # duplicate record
    find_record
    params['dup_fields'] += ',' if params['dup_fields'] # for easier field matching
    new_doc = duplicate_document(@record)
    create_new_empty_record(new_doc)
    update_standards()
    @record.save!

    index
  end
end

#destroyObject

Destroy action. Used also for enabling and disabling record.



485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
# File 'app/controllers/cmsedit_controller.rb', line 485

def destroy
  find_record
# Which permission is required to delete 
  permission = if params['operation'].nil?
    if @record.respond_to?('created_by') # needs can_delete_all if created_by is present and not owner
      (@record.created_by == session[:user_id]) ? DcPermission::CAN_DELETE : DcPermission::CAN_DELETE_ALL
    else
      DcPermission::CAN_DELETE    # by default
    end
  else # enable or disable record
    if @record.respond_to?('created_by')
      (@record.created_by == session[:user_id]) ? DcPermission::CAN_EDIT : DcPermission::CAN_EDIT_ALL
    else
      DcPermission::CAN_EDIT      # by default
    end
  end
  ok2delete = dc_user_can(permission)
#
  case
# not authorized    
  when !ok2delete then
    flash[:error] = t('drgcms.not_authorized')
    return index
  when params['operation'].nil? then
# Process before delete callback
    if (m = callback_method('before_delete') )
      ret = call_callback_method(m)
# Don't do anything if return is false
      return index if ret.class == FalseClass
    end
# document deleted
    if @record.destroy
      save_journal(:delete)
      flash[:info] = t('drgcms.record_deleted')
# Process after delete callback
      if (m = callback_method('after_delete') ) then call_callback_method(m) end
# Process return_to link
      return process_return_to(params[:return_to]) if params[:return_to]
    else
      flash[:error] = dc_error_messages_for(@record)
    end
    return index
# deaktivate document    
  when params['operation'] == 'disable' then
    if @record.respond_to?('active')
      @record.active = false
      save_journal(:update, @record.changes)
      update_standards()
      @record.save
      flash[:info] = t('drgcms.doc_disabled')
    end
# reaktivate document
  when params['operation'] == 'enable' then
    if @record.respond_to?('active')
      @record.active = true
      update_standards()
      save_journal(:update, @record.changes)
      @record.save
      flash[:info] = t('drgcms.doc_enabled')
    end
  end
#
  @parms['action'] = 'update'
  render action: :edit
end

#duplicate_document(source) ⇒ Object

Will create duplicate document of source document. This method is used for duplicating document and is called from create action.



374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
# File 'app/controllers/cmsedit_controller.rb', line 374

def duplicate_document(source)
  dest = {}
  source.attribute_names.each do |attribute_name|
    next if attribute_name == '_id' # don't duplicate _id
# if duplicate, string must be added. Useful for unique attributes
    add_duplicate = params['dup_fields'].to_s.match(attribute_name + ',')
    dest[attribute_name] = source[attribute_name]
    dest[attribute_name] << ' dup' if add_duplicate
  end
# embedded documents
  source.embedded_relations.keys.each do |embedded_name|
    next if source[embedded_name].nil? # it happens
    dest[embedded_name] = []
    source[embedded_name].each do |embedded|
      dest[embedded_name] << duplicate_embedded(embedded)
    end
  end
  dest
end

#duplicate_embedded(source) ⇒ Object

Duplicate embedded document. Since embedded documents are returned differently then top level document. Subroutine of duplicate_socument.



350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
# File 'app/controllers/cmsedit_controller.rb', line 350

def duplicate_embedded(source) #:nodoc:
# TODO Works for two embedded levels. Dies with third and more levels.
  dest = {}
  source.each do |attribute_name, value|
    next if attribute_name == '_id' # don't duplicate _id
    if value.class == Array
      dest[attribute_name] = []
      value.each do |ar|
        dest[attribute_name] << duplicate_embedded(ar)
      end
    else      
# if duplicate string must be added. Useful for unique attributes
      add_duplicate = params['dup_fields'].to_s.match(attribute_name + ',')
      dest[attribute_name] = value
      dest[attribute_name] << ' dup' if add_duplicate
    end
  end
  dest
end

#editObject

Edit action.



441
442
443
444
445
446
447
448
449
450
# File 'app/controllers/cmsedit_controller.rb', line 441

def edit
  find_record
  if (m = callback_method('before_edit') )
    ret = call_callback_method(m)
# Don't do anything if return is false
    return index if ret.class == FalseClass
  end  
  @parms['action'] = 'update'
  render action: :edit
end

#filterObject

Filter action.



267
268
269
# File 'app/controllers/cmsedit_controller.rb', line 267

def filter
  index
end

#indexObject

Index action.



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
255
256
257
258
259
260
261
262
# File 'app/controllers/cmsedit_controller.rb', line 218

def index
# If result_set is not defined on form, then it will fail. :return_to should know where to go
  if @form['result_set'].nil?
    return process_return_to(params[:return_to] || 'reload') 
  end
# for now enable only filtering of top level documents
  if @tables.size == 1 
    check_filter_options()
    check_sort_options()
  end  
# result set is defined by filter method in control object
  if @form['result_set']['filter']
    if respond_to?(@form['result_set']['filter'])
      @records = send @form['result_set']['filter']
# something iz wrong. flash[] should have explanation.
      if @records.class == FalseClass
        @records = []
        return render(action: :index)
      end
# pagination but only if not already set
      unless (@form['table'] == 'dc_memory' or @records.options[:limit])
        per_page = (@form['result_set']['per_page'] || 30).to_i
        @records = @records.page(params[:page]).per(per_page) if per_page > 0
      end
    else
      Rails.logger.error "Error: result_set:filter: #{@form['result_set']['filter']} not found in controls!"
    end
  else
    if @tables.size > 1 
      rec = @tables.first[0].find(@ids.first)          # top most document.id
      1.upto(@tables.size - 2) { |i| rec = rec.send(@tables[i][1].pluralize).find(@ids[i]) }  # find embedded childrens by ids
      @records = rec.send(@tables.last[1].pluralize)   # current embedded set
# sort by order if order field is present in model
      if @tables.last[1].classify.constantize.respond_to?(:order)
        @records = @records.order_by('order asc')
      end
    end
  end
#
  call_callback_method('dc_footer')
  respond_to do |format|
    format.html { render action:  :index }
    format.js   { render partial: :result }
  end
end

#loginObject

Login action. Used to login direct to CMS. It is mostly used when first time creating site and when something goes so wrong, that traditional login procedure is not available.

Login can be called directly with url site.com/cmsedit/login



295
296
297
298
# File 'app/controllers/cmsedit_controller.rb', line 295

def 
  session[:edit_mode] = 0 unless params[:ok]
  render action: 'login', layout: 'cms'
end

#logoutObject

Logout action. Used to logout direct from CMS.

Logout can be called directly with url site.com/cmsedit/logout



305
306
307
308
309
# File 'app/controllers/cmsedit_controller.rb', line 305

def logout 
  session[:edit_mode] = 0
  session[:user_id]   = nil
  render action: 'login', layout: 'cms'
end

#newObject

New action.



314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
# File 'app/controllers/cmsedit_controller.rb', line 314

def new
# clear flash messages.
  flash[:error] = flash[:warning] = flash[:info] = nil 
  create_new_empty_record
  if (m = callback_method('before_new') )
    ret = call_callback_method(m)
# Don't do anything if return is false
    return index if ret.class == FalseClass
  end  
  table = @tables.last[1] + '.'
# initial values set on page
  if cookies[:record] and cookies[:record].size > 0
    Marshal.load(cookies[:record]).each do |k,v|
      k = k.to_s
      if k.match(table)
        field = k.split('.').last
        @record.send("#{field}=", v) if @record.respond_to?(field)
      end
    end
  end
# initial values set in url
  params.each do |k,v|
    if k.match(table)
      field = k.split('.').last
      @record.send("#{field}=", v) if @record.respond_to?(field)
    end
  end
# This is how we set default values for new record
  dc_new_record() if respond_to?('dc_new_record') 
  @parms['action'] = 'create'
end

#set_session_filter(table_name) ⇒ Object

Will set session[:filter] and save last filter settings to session. subroutine of check_filter_options.



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
# File 'app/controllers/cmsedit_controller.rb', line 122

def set_session_filter(table_name)
  if params[:filter] == 'off' # clear all values
    session[table_name][:filter] = nil
    return
  end

  filter_value = if params[:filter_value].nil?
# NIL indicates that no filtering is needed        
    '#NIL'
  else     
    if params[:filter_value].class == String and params[:filter_value][0] == '@'
# Internal value. Remove leading @ and evaluate expression
      expression = DcInternals.get(params[:filter_value])
      eval(expression) rescue nil
    else
# No filter when empty      
      params[:filter_value] == '' ? '#NIL' : params[:filter_value] 
    end
  end
# if filter field parameter is omitted then just set filter value
  session[table_name][:filter] =
  if params[:filter_field].nil?
    saved = YAML.load(session[table_name][:filter])
    saved['value'] = filter_value
    saved.to_yaml
  else 
# As field defined. Split name and alternative input field
    field = if params[:filter_field].match(' as ')
      params[:filter_input] = params[:filter_field].split(' as ').last.strip
      params[:filter_field].split(' as ').first.strip
    else
      params[:filter_field]
    end
#    
    {'field'     => field, 
     'operation' => params[:filter_oper], 
     'value'     => filter_value,
     'input'     => params[:filter_input],
     'table'     => table_name }.to_yaml
  end
# must be. Otherwise kaminari includes parameter on paging
   params[:filter]        = nil 
   params[:filter_id]     = nil 
   params[:filter_oper]   = nil  
   params[:filter_input]  = nil 
   params[:filter_field]  = nil 
end

#showObject

Show displays record in readonly mode.



274
275
276
277
278
279
280
281
282
283
284
285
286
# File 'app/controllers/cmsedit_controller.rb', line 274

def show
  find_record
  if (m = callback_method('before_show') )
    ret = call_callback_method(m)
# Don't do anything if return is false
    if ret.class == FalseClass
      @form['readonly'] = nil # must be
      return index 
    end
  end  

  render action: 'edit', layout: 'cms'
end

#updateObject

Update action.



455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
# File 'app/controllers/cmsedit_controller.rb', line 455

def update
  find_record
# check if record was not updated in mean time
  if @record.respond_to?(:updated_at)
    if params[:last_updated_at].to_i != @record.updated_at.to_i
      flash[:error] = t('drgcms.updated_by_other')
      return render(action: :edit)
    end
  end
#   
  if dc_user_can(DcPermission::CAN_EDIT_ALL) or
    ( @record.respond_to?('created_by') and
      @record.created_by == session[:user_id] and
      dc_user_can(DcPermission::CAN_EDIT) )
#
    if save_data
      params[:return_to] = 'index' if params[:commit] == t('drgcms.save&back') # save & back
      @parms['action'] = 'update'
# Process return_to link
      return process_return_to(params[:return_to]) if params[:return_to]      
    end
  else
    flash[:error] = t('drgcms.not_authorized')
  end
  edit
end

#user_filter_options(model) ⇒ Object

Set aditional filter options when filter is defined by filter method in control object.



109
110
111
112
113
114
115
116
# File 'app/controllers/cmsedit_controller.rb', line 109

def user_filter_options(model) #:nodoc:
  table_name = @tables.first[1]
  if session[table_name]
    DcFilter.get_filter(session[table_name][:filter]) || model
  else
    model
  end
end