lib/rasti/db/collection.rb in rasti-db-1.4.0 vs lib/rasti/db/collection.rb in rasti-db-1.5.0

- old
+ new

@@ -1,12 +1,11 @@ module Rasti module DB class Collection - QUERY_METHODS = (Query::DATASET_CHAINED_METHODS + [:graph, :join, :count, :all, :each, :first, :pluck, :primary_keys, :any?, :empty?, :raw, :nql]).freeze + QUERY_METHODS = Query.public_instance_methods - Object.public_instance_methods - include Enumerable include Helpers::WithSchema class << self extend Sequel::Inflections @@ -14,12 +13,12 @@ def collection_name @collection_name ||= underscore(demodulize(name)).to_sym end - def collection_fields - @collection_fields ||= model.attributes - relations.keys + def collection_attributes + @collection_attributes ||= model.attributes - relations.keys end def primary_key @primary_key ||= :id end @@ -78,11 +77,11 @@ raise "Query #{name} already exists" if queries.key? name queries[name] = lambda || block define_method name do |*args| - query.instance_exec(*args, &self.class.queries[name]) + default_query.instance_exec(*args, &self.class.queries.fetch(name)) end end end @@ -91,10 +90,16 @@ def initialize(db, schema=nil) @db = db @schema = schema ? schema.to_sym : nil end + QUERY_METHODS.each do |method| + define_method method do |*args, &block| + default_query.public_send method, *args, &block + end + end + def dataset db[qualified_collection_name] end def insert(attributes) @@ -170,16 +175,10 @@ def find_graph(primary_key, *relations) where(self.class.primary_key => primary_key).graph(*relations).first end - QUERY_METHODS.each do |method| - define_method method do |*args, &block| - query.public_send method, *args, &block - end - end - def exists?(filter=nil, &block) build_query(filter, &block).any? end def detect(filter=nil, &block) @@ -197,19 +196,22 @@ def qualified_collection_name schema.nil? ? Sequel[self.class.collection_name] : Sequel[schema][self.class.collection_name] end - def query - Query.new self.class, dataset, [], schema + def default_query + Query.new collection_class: self.class, + dataset: dataset.select_all(self.class.collection_name), + schema: schema end def build_query(filter=nil, &block) raise ArgumentError, 'must specify filter hash or block' if filter.nil? && block.nil? + if filter - query.where filter + default_query.where filter else - block.arity == 0 ? query.instance_eval(&block) : block.call(query) + block.arity == 0 ? default_query.instance_eval(&block) : block.call(default_query) end end def split_related_attributes(attributes) relation_names = self.class.relations.values.select(&:many_to_many?).map(&:name) \ No newline at end of file