Class: Coupler::Models::Result

Inherits:
Sequel::Model
  • Object
show all
Includes:
CommonModel
Defined in:
lib/coupler/models/result.rb

Instance Method Summary collapse

Methods included from CommonModel

#after_destroy, #after_save, #before_create, #before_update, included, #save!, #touch!

Instance Method Details

#groups_datasetObject



25
26
27
28
29
30
31
32
33
34
35
# File 'lib/coupler/models/result.rb', line 25

def groups_dataset
  if block_given?
    scenario.local_database do |db|
      yield db[groups_table_name]
    end
    nil
  else
    db = scenario.local_database
    db[groups_table_name]
  end
end

#groups_records_datasetObject



41
42
43
44
45
46
47
48
49
50
51
# File 'lib/coupler/models/result.rb', line 41

def groups_records_dataset
  if block_given?
    scenario.local_database do |db|
      yield db[groups_records_table_name]
    end
    nil
  else
    db = scenario.local_database
    db[groups_records_table_name]
  end
end

#groups_records_table_nameObject



37
38
39
# File 'lib/coupler/models/result.rb', line 37

def groups_records_table_name
  :"groups_records_#{run_number}"
end

#groups_table_nameObject



21
22
23
# File 'lib/coupler/models/result.rb', line 21

def groups_table_name
  :"groups_#{run_number}"
end

#snapshotObject



7
8
9
10
11
12
13
14
15
16
17
18
19
# File 'lib/coupler/models/result.rb', line 7

def snapshot
  origin_scenario = Scenario.as_of_version(scenario_id, scenario_version)
  time = origin_scenario.updated_at
  project = Project.as_of_time(origin_scenario.project_id, time)
  resource_1 = Resource.as_of_time(origin_scenario.resource_1_id, time)
  resource_2 = Resource.as_of_time(origin_scenario.resource_2_id, time)
  {
    :project => project,
    :scenario => origin_scenario,
    :resource_1 => resource_1,
    :resource_2 => resource_2
  }
end

#to_csvObject



53
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
# File 'lib/coupler/models/result.rb', line 53

def to_csv
  # grab primary keys and datasets from the scenario's resources
  rdatasets = []
  rkeys = []
  headers = []
  scenario.resources.each do |resource|
    field_names = resource.selected_fields_dataset.select(:name).order(:id).naked.map { |f| f[:name].to_sym }
    rdatasets << resource.final_dataset.select(*field_names)
    rkeys << resource.primary_key_sym
    headers |= field_names
  end
  headers << :coupler_group_id

  csv = FasterCSV.new("", :headers => true)
  csv << headers

  groups_records_dataset.each do |group_record|
    # 'which' is either 0 or 1 (or nil for self-linkages)
    # rdatasets can be either length 1 or 2
    which = group_record[:which] || 0
    rdataset = rdatasets[-which]
    rkey = rkeys[-which]

    record = rdataset[rkey => group_record[:record_id]]
    record[:coupler_group_id] = group_record[:group_id]
    csv << record   # slots everything correctly
  end

  rdatasets.each { |r| r.db.disconnect }
  csv.string
end