Reputation: 1836
I have model named Order which belongs to User, Admin, Device etc. I want to see total of orders for specific object like user.
so I have to write in user.rb model
def total_sales
// there are some dates & status conditions too
orders.sum(:total)
end
but for admin, device etc. I have to write exact same code in admin.rb & device.rb
I want to write code on just one place & write everywhere, I was thinking to write a generic class like
class Calculate
def initialize(object)
@object = object
end
def total_sales
// there are some dates & status conditions too
@object.orders.sum(:total)
end
end
and than call it like
//sales of user
object = Calculate.new(user)
object.total_sales
//sales of admin
object = Calculate.new(admin)
object.total_sales
But I am not sure if this is standard way, Whats the better way achieve this.
Upvotes: 1
Views: 116