编写activerecord替代方案时遇到的问题

时间:2016-08-22 11:46:17

标签: ruby activerecord rails-activerecord named-scope

我想为activerecord命名范围创建一个替代方案。

module M
  def self.included(klass)
    klass.extend ClassMethods
    klass.class_variable_set("@@obj_array", [])
  end
  module ClassMethods

    def attr_accessor (*args)
      args.each do |method_name|
        define_method :method_name do
        end
      end
      super
    end

    def where(*attr)
      obj1 = []
      a = attr.keys.map { |i| i.to_s }.join()
      c = class_variable_get("@@obj_array")
      c.each do |obj|
        if obj.instance_variable_get("@#{a}") == attr.values.map { |i| i.to_s }.join().to_i || obj.instance_variable_get("@#{a}") == attr.values.map { |i| i.to_s }.join().to_s
          obj1 << obj
        end
      end
      obj1
    end

    def scope (name, lambda)
      self.class_eval do

        define_singleton_method "#{name}" do
          lambda.call
        end
      end
    end
  end

  def initialize
    self.class.class_variable_get("@@obj_array") << self
  end
end

class User
  include M
  attr_accessor :age, :email, :status
  scope :children, ->{ where(age: 17) }
  scope :active, ->{ where(status: "active") }
  scope :person, ->{ where(email: "foo@abc..com")}

  # scope :some, -> {where(age: 5, email: 'fdsa@fjdsk.com')}

end

a = User.new
b = User.new
c = User.new
a.age = 17
b.age = 12
b.status = "active"
c.email = "foo@abc..com"
# p User.children.all
# p User.active.all
#User.children.active.all

我已经写了上面的代码。 User.active返回状态为活动状态的对象数组。我做到了。

User.active.all应返回状态为活动的对象数组。不能用所有方法 User.children.active.all应该让年龄在17岁且身份活跃的儿童退回。我不知道该怎么做。

0 个答案:

没有答案