Class: Bmg::Redis::Relation

Inherits:
Object
  • Object
show all
Includes:
Bmg::Relation
Defined in:
lib/bmg/redis/relation.rb

Constant Summary collapse

DEFAULT_OPTIONS =
{
  serializer: :marshal
}

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(type, options) ⇒ Relation

Returns a new instance of Relation.



10
11
12
13
14
15
16
# File 'lib/bmg/redis/relation.rb', line 10

def initialize(type, options)
  @type = type
  @options = DEFAULT_OPTIONS.merge(options)

  serializer!
  candidate_key!
end

Instance Attribute Details

#typeObject

Returns the value of attribute type.



17
18
19
# File 'lib/bmg/redis/relation.rb', line 17

def type
  @type
end

Instance Method Details

#delete(predicate = Predicate.tautology) ⇒ Object



57
58
59
60
61
62
63
64
65
66
# File 'lib/bmg/redis/relation.rb', line 57

def delete(predicate = Predicate.tautology)
  keys = self
    .each
    .select{|tuple| predicate.call(tuple) }
    .map{|tuple| extract_key(tuple) }

  redis.del(*keys)

  self
end

#eachObject



22
23
24
25
26
27
28
29
30
# File 'lib/bmg/redis/relation.rb', line 22

def each
  return to_enum unless block_given?

  redis.scan_each(match: "#{key_prefix}:*") do |key|
    tuple_str = redis.get(key)
    tuple = serializer.deserialize(tuple_str)
    yield(tuple)
  end
end

#insert(tuple_or_tuples) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/bmg/redis/relation.rb', line 34

def insert(tuple_or_tuples)
  case tuple_or_tuples
  when Hash
    key = extract_key(tuple_or_tuples)
    serialized = serializer.serialize(tuple_or_tuples)
    redis.set(key, serialized)
  else
    tuple_or_tuples.each do |tuple|
      insert(tuple)
    end
  end
  self
end

#update(updating, predicate = Predicate.tautology) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/bmg/redis/relation.rb', line 48

def update(updating, predicate = Predicate.tautology)
  each do |tuple|
    next unless predicate.call(tuple)

    insert(tuple.merge(updating))
  end
  self
end