forked from elastic/elasticsearch-rails
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrepository.rb
77 lines (67 loc) · 2.32 KB
/
repository.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
77
module Elasticsearch
module Persistence
# Delegate methods to the repository (acting as a gateway)
#
module GatewayDelegation
def method_missing(method_name, *arguments, &block)
gateway.respond_to?(method_name) ? gateway.__send__(method_name, *arguments, &block) : super
end
def respond_to?(method_name, include_private=false)
gateway.respond_to?(method_name) || super
end
def respond_to_missing?(method_name, *)
gateway.respond_to?(method_name) || super
end
end
# When included, creates an instance of the {Repository::Class Repository} class as a "gateway"
#
# @example Include the repository in a custom class
#
# require 'elasticsearch/persistence'
#
# class MyRepository
# include Elasticsearch::Persistence::Repository
# end
#
module Repository
def self.included(base)
gateway = Elasticsearch::Persistence::Repository::Class.new host: base
# Define the instance level gateway
#
base.class_eval do
define_method :gateway do
@gateway ||= gateway
end
include GatewayDelegation
end
# Define the class level gateway
#
(class << base; self; end).class_eval do
define_method :gateway do |&block|
@gateway ||= gateway
@gateway.instance_eval(&block) if block
@gateway
end
include GatewayDelegation
end
# Catch repository methods (such as `serialize` and others) defined in the receiving class,
# and overload the default definition in the gateway
#
def base.method_added(name)
if :gateway != name && respond_to?(:gateway) && (gateway.public_methods - Object.public_methods).include?(name)
gateway.define_singleton_method(name, self.new.method(name).to_proc)
end
end
end
# Shortcut method to allow concise repository initialization
#
# @example Create a new default repository
#
# repository = Elasticsearch::Persistence::Repository.new
#
def new(options={}, &block)
Elasticsearch::Persistence::Repository::Class.new( {index: 'repository'}.merge(options), &block )
end; module_function :new
end
end
end