Adding methods to objects that were created on the fly

Hey all,

I call this method to create two objects with certain attributes but
because of this, these objects do not have the attributes of any of
the report object instantiated normally:

def self.sum_distance_by_date
find_by_sql(“SELECT date_trunc(‘day’, time), SUM(distance) FROM
reports GROUP BY date_trunc(‘day’, time)”)
end

So this method creates two report objects with a sum method and
date_trunc method but none of the instance methods assigned to regular
report object instances. The problem is the sum method returns a value
that I need to modify and I am not sure how to create an extra method
for these two objects to do that. I try adding this to report model:

def distance_miles_for_report
self.sum * 0.000621371192
end

def distance_format
if self.has_attribute?(:distance)
return sprintf("%.2f mi.", distance_miles)
elsif self.has_attribute?(:sum)
return sprintf("%.2f mi.", distance_miles_for_report)
end
end

But simply adding this instance method to report model does not copy
the methods over to the object instances created with
sum_distance_by_date. So I am wondering how I can ensure that the
distance_format and distance_miles_for_report method are copied to
objects created with sum_distance_by_date.

thanks for response

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs