Class: Renalware::Pathology::CurrentObservationsForDescriptionsQuery

Inherits:
Object
  • Object
show all
Defined in:
app/models/renalware/pathology/current_observations_for_descriptions_query.rb

Overview

Responsible for finding the current observations for a patient for the specified observation descriptions. It returns a result for each observation description, nulls for missing observations for that description.

Note the query does not accept a relation as trying to compose it may break the desired result set.

Instance Method Summary collapse

Constructor Details

#initialize(patient:, descriptions:) ⇒ CurrentObservationsForDescriptionsQuery

Returns a new instance of CurrentObservationsForDescriptionsQuery.



16
17
18
19
# File 'app/models/renalware/pathology/current_observations_for_descriptions_query.rb', line 16

def initialize(patient:, descriptions:)
  @patient = patient
  @descriptions = descriptions
end

Instance Method Details

#callObject

rubocop:disable Metrics/MethodLength If no observations found, returns nil values for all descriptions, e.g.

<ActiveRecord::Relation [
  #<Renalware::Pathology::Observation id: nil, ...(all nil)>,
  #<Renalware::Pathology::Observation id: nil, ...(all nil)>,
  ...
]

or if results found: #<ActiveRecord::Relation [

#<Renalware::Pathology::Observation id: 199, result: "48", observed_at: "2016-03-15..>,
#<Renalware::Pathology::Observation id: 201, result: "71", observed_at: "2016-03-15..>,
...

]



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'app/models/renalware/pathology/current_observations_for_descriptions_query.rb', line 34

def call
  # Note:
  #
  #   CurrentObservation.where(patient: patient, description_name: descriptions.map(&:name))
  #
  # is potentially a replacement for the SQL below, but it does not return
  # null values. We'd need a bit of SQL to join again onto pathology_observation_descriptions
  # and fill the missing observations with NULLs in order to keep the output of this query
  # the same.
  Observation
    .includes(:description)
    .select(<<-SQL.squish)
    .joins(<<-SQL.squish)
    .joins(<<-SQL.squish)
      RIGHT JOIN pathology_observation_descriptions
      ON pathology_observations.description_id = pathology_observation_descriptions.id
    SQL
    .order("pathology_observation_descriptions.id")
    .ordered
    .where(["pathology_observation_requests.patient_id = ? OR " \
            "pathology_observation_requests.patient_id IS NULL", patient.id])
    .where(pathology_observation_descriptions: { id: descriptions })
end