Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
AREL examples
# frozen_string_literal: true
require('method_object')
# Handles the measurement year window, including scopes to allow querying of QDM
# models within specified date ranges relative to the measurement year.
MeasurementYear = Struct.new(:program) do
def initialize(program:)
super(program)
end
def scope(qdm_model)
Scope.call(program: program, qdm_model: qdm_model)
end
def last_date_of_year
Program
.program_module(program)
.current_measurement_year_start_datetime
.end_of_year
.to_date
end
def patient_age_in_range_at_year_end(min_age, max_age)
Patient
.age_in_range_on_date(
date: last_date_of_year,
min_age: min_age,
max_age: max_age,
)
end
def patient_age_in_year_range_at_year_end(min_age, max_age)
patient_age_in_range_at_year_end(min_age.years, (max_age + 1).years)
end
Scope = MethodObject.new(:program, :qdm_model) do
def call
qdm_model
.before_end_of_measurement_year(
measurement_year_start_datetime:
current_measurement_year_start_datetime,
)
.extending(Scopes).tap do |scope|
scope.current_measurement_year_start_datetime =
current_measurement_year_start_datetime
end
end
def current_measurement_year_start_datetime
Program.program_module(program).current_measurement_year_start_datetime
end
end
# Contains only methods which need to know the measurement year start date
module Scopes
attr_writer(:current_measurement_year_start_datetime)
def in_measurement_year
in_previous_n_years(1)
end
def offset(years)
@current_measurement_year_start_datetime -= years.years
self
end
def in_previous_n_years(years)
where(
start_datetime
.gteq(beginning_of_next_measurement_year - years.years)
.and(
start_datetime.lt(beginning_of_next_measurement_year),
),
)
end
def in_previous_n_months(months)
where(
start_datetime
.gteq(beginning_of_next_measurement_year - months.months)
.and(
start_datetime.lt(beginning_of_next_measurement_year),
),
)
end
def before_6_months_of_end_of_measurement_year
where(
start_datetime.lt(beginning_of_next_measurement_year - 6.months),
)
end
private
def start_datetime
arel_table[:start_datetime]
end
def beginning_of_next_measurement_year
@current_measurement_year_start_datetime.next_year
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment