lundi 28 mars 2022

Alias Rails Model with Scope as different class

I have a rails model with a scope that I would like to be able to use as a separate class for future semantics consistency. An example of this would be -

class User
  scope :admin, => { where(admin: true) }
end

For my purposes, it's important that documentation and code is clearer than calling User.admin whenever I want to work with just admins, without creating a separate model. (Schema is identical, and there is more than 1 scope I need to move into a separate object).

My current solution is

class Admin
  @@receiver = User.admin

  def method_missing(m, *args, &block)
    @@receiver.send(m, *args, &block)
  end

  def self.method_missing(m, *args, &block)
    @@receiver.send(m, *args, &block)
  end
end

This way, I can use Admin as an ActiveRecord::Relation where ever I need.

Is this an effective means of solving the issue? Because of gems we're running, I cannot inherit User, or it will start using STI and get really weird really quickly.

Aucun commentaire:

Enregistrer un commentaire