Ash Framework: Calculations
How to use calculation to build another calculation. What?

Intro
Recently, I was tasked with creating a calculation to run an Oban job using ash_oban. I needed to determine whether a specific record met the criteria using this calculation. Here's what I did to achieve that.
calculations do
calculate :should_this_record_run_oban_job?, :boolean do
calculation expr(
# this is where the problem I need to solve.
true
)
end
end
Problem 1: How can I build the criteria that I need?
calculations do
calculate :should_this_record_run_oban_job?, :boolean do
calculation expr(
# this is where the problem I need to solve.
true
)
end
end
When performing calculations, you can use fragments or directly access the attributes needed to create specific conditions. Initially, I did something like this.
calculations do
calculate :should_this_record_run_oban_job?, :boolean do
calculation expr(
inserted_at <= ago(24, :hour) and name == "freddy" and
age >= 18
)
end
end
It seems pretty straightforward right? BUT what I discovered is somehow more readable and organized.
What I discovered
What I discovered is that, you can create multiple calculations and combine them according to your needs.
calculations do
calculate :active_last_24_hours_ago?, :boolean do
calculation expr(inserted_at <= ago(24, :hour)
end
calculate :is_his_name_freddy?, :boolean do
calculation expr(name == "freddy")
end
calculte :is_age_18_or_more?, :boolean do
calculation expr(age >= 18)
end
calculate :should_this_record_run_oban_job?, :boolean do
calculation expr(
active_last_24_hours_ago? and is_his_name_freddy? and is_age_18_or_more?
)
end
end
Now, I can use the should_this_record_run_oban_job? to determine whether each record should run an oban job or not.
Happy coding!




