I have method in my rails model which returns anonymous class:
def today_earnings
Class.new do
def initialize(user)
@user = user
end
def all
@user.store_credits.where(created_at: Time.current.beginning_of_day..Time.current.end_of_day)
end
def unused
all.map { |el| el.amount - el.amount_used }.instance_eval do
def to_f
reduce(:+)
end
end
end
def used
all.map(&:amount_used).instance_eval do
def to_f
reduce(:+)
end
end
end
end.new(self)
end
I want to achieve possibility to chain result in that way user.today_earning.unused.to_f and I have some problems with instance eval because when I call to_f on result it's undefined method, I guess it is due to ruby copying returned value so the instance gets changed, is it true? And if I'm correct how can I change the code to make it work. Also I'm wondering if making new model can be better solution than anomyous class thus I need advice if anonymous class is elegant in that case and if so how can I add to_f method to returned values
instance_eval, you only defineto_f, so you then try to call the methodto_fon the:to_fSymbol. You might try to addselfat the end of theinstance_evalblock but it feels like a hack.store_creditstable withamountandamount_usedcolumns? If so, the obvious solution would be a database query for getting the results.