It's a useful skill to extend build-in ruby classes in Rails. And it turns out to be fairly straightforward. We're going to use an example to explain how to do that.
Use case: we have an array of scheduled jobs, work orders and events. We'd like to update all the schedules at a given set time if certain conditions met.
In app/models/application_record.rb
, we could extend the Array
class methods.
class Array
def update_all_schedule(run_at:)
self.map do |j|
next if !j.try(:parent)
j.reschedule(run_at)
end
end
end
Now everywhere that we want to update the schedule, we could do:
WorkOrder.where(owner: 'admin').update_all_schedule(run_at: 2.days.from.now)
That gives us the ability of putting all the logic in the extended class method and dry up the code.