/
cassanity.rb
76 lines (61 loc) · 2.11 KB
/
cassanity.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
require 'adapter'
require 'forwardable'
require 'cassanity'
module Adapter
module Cassanity
extend Forwardable
# Public
def read(key, options = nil)
operation_options = {where: where(key)}
adapter_options = @options[:read]
arguments = update_arguments(operation_options, adapter_options, options)
rows = @client.select(arguments)
rows.empty? ? nil : rows.first
end
# Public
def write(key, attributes, options = nil)
operation, operation_options = prepare_operation(options, :update, set: attributes, where: where(key))
adapter_options = @options[:write]
arguments = update_arguments(operation_options, adapter_options, options)
@client.send(operation, arguments)
end
# Public
def delete(key, options = nil)
operation_options = {where: where(key)}
adapter_options = @options[:delete]
arguments = update_arguments(operation_options, adapter_options, options)
@client.delete(arguments)
end
# Public
def clear(options = nil)
@client.truncate
end
# Private
def where(key)
primary_key = @options.fetch(:primary_key)
{primary_key => key}
end
# Private.
def prepare_operation(options, operation, operation_options)
if options && (modifications = options[:modifications]) && modifications.any?
operation_options = {modifications: [ [operation, operation_options], *modifications ]}
operation = :batch
end
[ operation, operation_options ]
end
# Private
def update_arguments(operation_options, adapter_options, method_options)
keys = operation_options.keys
if !adapter_options.nil? && !adapter_options.empty?
filtered_options = adapter_options.reject { |key| keys.include?(key) }
operation_options.update(filtered_options)
end
if !method_options.nil? && !method_options.empty?
filtered_options = method_options.reject { |key| keys.include?(key) }
operation_options.update(filtered_options)
end
operation_options
end
end
end
Adapter.define(:cassanity, Adapter::Cassanity)