Muhammad Faisal Iqbal
Muhammad Faisal Iqbal

Reputation: 1836

Rails generic method for multiple classes

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

Answers (1)

Salil
Salil

Reputation: 47472

Use mixin for this, create a module like below.

module CommonMethods
  def total_sales
    // there are some dates & status conditions too
    self.orders.sum(:total)
  end
end

include the module in each class like User, Admin, Device etc.

class User
  include CommonMethods
end

Upvotes: 2

Related Questions