Class: Godfather::Manager

Inherits:
Object
  • Object
show all
Defined in:
lib/godfather/manager.rb

Instance Method Summary collapse

Constructor Details

#initialize(controller, model, scope_js, data_js, extra_find_scopes_js = '[]') ⇒ Manager

Returns a new instance of Manager.



3
4
5
6
7
8
9
10
11
# File 'lib/godfather/manager.rb', line 3

def initialize(controller, model, scope_js, data_js, extra_find_scopes_js = '[]')
  @model = model
  @scope = Godfather::Data.new(controller, scope_js)
  @data = Godfather::Data.new(controller, data_js).to_h

  @extra_find_scopes = JSON.parse(extra_find_scopes_js).map do |extra_scope|
    Godfather::Data.new(controller, extra_scope)
  end
end

Instance Method Details

#create_from_dataObject



24
25
26
# File 'lib/godfather/manager.rb', line 24

def create_from_data
  @model.where(@scope.to_h).create(@data)
end

#destroy_from_dataObject



41
42
43
# File 'lib/godfather/manager.rb', line 41

def destroy_from_data
  @model.find(@data['id']).destroy
end

#find_scoped_recordsObject



13
14
15
16
17
18
19
20
21
22
# File 'lib/godfather/manager.rb', line 13

def find_scoped_records
  records = []
  records << @scope.records(@model)

  @extra_find_scopes.each do |extra_scope|
    records << extra_scope.records(@model)
  end

  records.map { |record| record.where(@data) }.flatten
end

#update_from_dataObject



28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/godfather/manager.rb', line 28

def update_from_data
  new_data = @data
  id = new_data.delete('id')

  permitted_cols = @model.column_names
  updatable_data = new_data.slice(*permitted_cols)

  record = @model.find(id)
  record.update(updatable_data)

  record
end