relation.rb
class Relation
delegate :to_xml, :to_yaml, :length, :collect, :map, :each, :all?, :include?, :to_ary, :join, to: :to_a
def initialize options = {}
raise 'class is not initialize' if options[:model].blank?
@class_name = options[:model]
@where = options[:where] || []
@limit = options[:limit] || []
@order = options[:order] || []
@page = options[:page] || []
@per_page = []
@records = []
end
def inspect
to_a
"#<#{self.class}: records: #{self.instance_variable_get(:@records)} attrs: #{self.instance_values}>"
end
%w/where limit order page per_page/.each do |m|
define_method m do |args=nil|
self.instance_variable_get("@#{m}".to_sym) << args if args.present?
self
end
end
def to_a
load_records
@records
end
def load_records
#查询集中在这里
@records = ['a', 'b', 'c']
end
end
cat.rb
class Cat
delegate :select, :group, :order, :reorder, :limit, :joins, :where, :preload, :eager_load, :includes, :from, :lock, :readonly, :having, :create_with, to: :scoped
def scoped
@model ||= self.class.const_set 'Relation', Class.new(Relation)
@model.new(model: self.class)
end
end
subcat.rb
class SubCat < Cat
end
c = SubCat.new
#<SubCat:0x007fe078c21658>
c.where.class
SubCat::Relation
c.where('1=1').order('test asc').limit(1)
#<SubCat::Relation: records: ["a", "b", "c"] attrs: {"class_name"=>SubCat, "where"=>["1=1"], "limit"=>[1], "order"=>["test asc"], "page"=>[], "per_page"=>[], "records"=>["a", "b", "c"]}>
c.where('1=1').order('test asc').limit(1).each{|c| p c }
"a"
"b"
"c"
["a", "b", "c"]