Jul 06
Rails in practice - Compare records
We have Travel object which defines travel_on attribute. Now, when I want to compare Travel objects, I can use:
raise "Cannot come before you leave" unless departure.travel_on > arrival.tavel_on
Or sort travel array with:
journeys.sort {|a,b| a.travel_on<=>b.travel_on}
This would work, but it is not very readable and DRY. If we include Comparable mixin in Travel , and define <=> operator we would get conventional comparison operators (<, <=, ==, >=, and >) including the method between? for free. Our code would now look:
class Travel < ActiveRecord::Base
include Comparable
def <=>(other)
self.travel_on<=>other.travel_on
end
end
...
raise "Cannot come before you leave" unless departure > arrival
...
journeys.sort
...
some_other_travel.between?(arrival, departure)
I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working at
blog comments powered by Disqus