lib/model_set.rb in ninjudd-model_set-0.10.4 vs lib/model_set.rb in ninjudd-model_set-0.10.5

- old
+ new

@@ -54,11 +54,11 @@ define_method(action) do |models| anchor!(:set) query.send(action, as_ids(models)) self end - end + end clone_method :+, :add! clone_method :-, :subtract! clone_method :&, :intersect! @@ -66,10 +66,17 @@ alias concat add! alias delete subtract! alias without! subtract! clone_method :without + clone_method :shuffle + def shuffle!(seed = nil) + reanchor!(:set) + query.shuffle!(seed) + self + end + def include?(model) model_id = as_id(model) model_ids.include?(model_id) end @@ -166,18 +173,21 @@ end self.ids = filtered_ids self end - def select(&block) - self.clone.select!(&block) + def select(limit = nil, &block) + self.clone.select!(limit, &block) end - def select! + def select!(limit = nil) filtered_ids = [] self.each do |model| - filtered_ids << model.send(id_field) if yield model + if yield model + filtered_ids << model.send(id_field) + break if filtered_ids.size == limit + end end self.ids = filtered_ids self end @@ -235,21 +245,21 @@ end def sort!(&block) block ||= lambda {|a,b| a <=> b} sorted_ids = to_a.sort(&block).collect {|m| m.id} - model_ids.reorder!(sorted_ids) + reorder!(sorted_ids) self end def sort_by(&block) self.clone.sort_by!(&block) end def sort_by!(&block) sorted_ids = to_a.sort_by(&block).collect {|m| m.id} - model_ids.reorder!(sorted_ids) + reorder!(sorted_ids) self end def partition_by(filter) filter = filter.to_s @@ -338,10 +348,17 @@ if not query_type?(query_class) self.query = query_class.new(self, *args) end self end + + def reanchor!(type = default_query_type, *args) + # Force anchoring even if you are already anchored to this type. + return unless type + self.query = query_class(type).new(self, *args) + self + end def default_query_type :sql end @@ -362,10 +379,11 @@ # Don't change the query engine by default anchor!( extract_opt(:query_type, args) ) # Use the default query engine if the the current engine doesn't respond to the method. anchor!(default_query_type) unless query.respond_to?(method_name) + anchor!(:set) if [:limit!, :page!].include?(method_name) and not query.limit_enabled? query.send(method_name, *args) self end end @@ -377,11 +395,10 @@ opt end def add_fields!(fields) raise 'cannot use both add_fields and include_models' if @included_models - ( @add_fields ||= {} ).merge!(fields) # We have to reload the models because we are adding additional fields. self.clear_cache! end @@ -462,10 +479,10 @@ set.page!(opts[:page]) if opts[:page] set end def self.find_by_sql(sql) - query = RawSQLQuery.new + query = RawSQLQuery.new(self) query.sql = sql new(query) end def self.constructor(filter_name, opts = nil)