lib/ohm.rb in ohm-1.0.0.alpha1 vs lib/ohm.rb in ohm-1.0.0.alpha2

- old
+ new

@@ -292,10 +292,23 @@ # def add(model) key.sadd(model.id) end + # Remove a model directly from the set. + # + # Example: + # + # user = User.create + # post = Post.create + # + # user.posts.delete(post) + # + def delete(model) + key.srem(model.id) + end + # Chain new fiters on an existing set. # # Example: # # set = User.find(name: "John") @@ -306,10 +319,38 @@ keys.push(key) MultiSet.new(keys, namespace, model) end + # Reduce the set using any number of filters. + # + # Example: + # + # set = User.find(name: "John") + # set.except(country: "US") + # + # # You can also do it in one line. + # User.find(name: "John").except(country: "US") + # + def except(dict) + MultiSet.new([key], namespace, model).except(dict) + end + + # Do a union to the existing set using any number of filters. + # + # Example: + # + # set = User.find(name: "John") + # set.union(name: "Jane") + # + # # You can also do it in one line. + # User.find(name: "John").union(name: "Jane") + # + def union(dict) + MultiSet.new([key], namespace, model).union(dict) + end + # Replace all the existing elements of a set with a different # collection of models. This happens atomically in a MULTI-EXEC # block. # # Example: @@ -370,13 +411,55 @@ keys.push(*self.keys) MultiSet.new(keys, namespace, model) end + # Reduce the set using any number of filters. + # + # Example: + # + # set = User.find(name: "John") + # set.except(country: "US") + # + # # You can also do it in one line. + # User.find(name: "John").except(country: "US") + # + def except(dict) + sdiff.push(*model.filters(dict)).uniq! + + return self + end + + # Do a union to the existing set using any number of filters. + # + # Example: + # + # set = User.find(name: "John") + # set.union(name: "Jane") + # + # # You can also do it in one line. + # User.find(name: "John").union(name: "Jane") + # + def union(dict) + sunion.push(*model.filters(dict)).uniq! + + return self + end + private + def sunion + @sunion ||= [] + end + + def sdiff + @sdiff ||= [] + end + def execute key = namespace[:temp][SecureRandom.uuid] key.sinterstore(*keys) + key.sdiffstore(key, *sdiff) if sdiff.any? + key.sunionstore(key, *sunion) if sunion.any? begin yield key ensure key.del