Module: Motor::Dashboards::Persistance

Defined in:
lib/motor/dashboards/persistance.rb

Constant Summary collapse

TitleAlreadyExists =
Class.new(StandardError)

Class Method Summary collapse

Class Method Details

.archive_with_existing_name(dashboard) ⇒ Object


59
60
61
62
# File 'lib/motor/dashboards/persistance.rb', line 59

def archive_with_existing_name(dashboard)
  Motor::Dashboard.where(['title = ? AND id != ?', dashboard.title, dashboard.id])
                  .update_all(deleted_at: Time.current)
end

.assign_attributes(dashboard, params) ⇒ Object


52
53
54
55
56
57
# File 'lib/motor/dashboards/persistance.rb', line 52

def assign_attributes(dashboard, params)
  dashboard.assign_attributes(params.slice(:title, :description, :preferences))
  dashboard.updated_at = [params[:updated_at], Time.current].min if params[:updated_at].present?

  Motor::Tags.assign_tags(dashboard, params[:tags])
end

.build_from_params(params, current_user = nil) ⇒ Object


10
11
12
13
14
15
16
# File 'lib/motor/dashboards/persistance.rb', line 10

def build_from_params(params, current_user = nil)
  dashboard = assign_attributes(Dashboard.new, params)

  dashboard.author = current_user

  dashboard
end

.create_from_params!(params, current_user = nil) ⇒ Object


18
19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/motor/dashboards/persistance.rb', line 18

def create_from_params!(params, current_user = nil)
  raise TitleAlreadyExists if Dashboard.exists?(title: params[:title])

  dashboard = build_from_params(params, current_user)

  ApplicationRecord.transaction do
    dashboard.save!
  end

  dashboard
rescue ActiveRecord::RecordNotUnique
  retry
end

.title_already_exists?(dashboard) ⇒ Boolean

Returns:

  • (Boolean)

64
65
66
67
68
69
70
# File 'lib/motor/dashboards/persistance.rb', line 64

def title_already_exists?(dashboard)
  if dashboard.new_record?
    Motor::Dashboard.exists?(title: dashboard.title)
  else
    Motor::Dashboard.exists?(['title = ? AND id != ?', dashboard.title, dashboard.id])
  end
end

.update_from_params!(dashboard, params, force_replace: false) ⇒ Object


32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/motor/dashboards/persistance.rb', line 32

def update_from_params!(dashboard, params, force_replace: false)
  tag_ids = dashboard.tags.ids

  dashboard = assign_attributes(dashboard, params)

  raise TitleAlreadyExists if !force_replace && title_already_exists?(dashboard)

  ApplicationRecord.transaction do
    archive_with_existing_name(dashboard) if force_replace

    dashboard.save!
  end

  dashboard.touch if tag_ids.sort != dashboard.tags.reload.ids.sort && params[:updated_at].blank?

  dashboard
rescue ActiveRecord::RecordNotUnique
  retry
end