Class: Exid::Record

Inherits:
Module
  • Object
show all
Defined in:
lib/exid/record.rb

Defined Under Namespace

Classes: Entry

Constant Summary collapse

MUTEX =
Mutex.new

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(prefix, field) ⇒ Record



31
32
33
34
35
36
37
38
39
# File 'lib/exid/record.rb', line 31

def initialize(prefix, field)
  Exid.configuration.validate_prefix(prefix)

  @module_static = build_module_static(prefix, field)
  @module_value = build_module_value(prefix, field)
  @module_shared = build_module_shared(prefix, field)

  super()
end

Class Method Details

.fetch(eid) ⇒ Object



77
# File 'lib/exid/record.rb', line 77

def self.fetch(eid) = finder(eid).first

.fetch!(eid) ⇒ Object



79
# File 'lib/exid/record.rb', line 79

def self.fetch!(eid) = finder(eid).sole

.find_module(prefix) ⇒ Object



65
66
67
68
# File 'lib/exid/record.rb', line 65

def self.find_module(prefix)
  registered_modules.detect { _1.prefix == prefix } or
    raise Error, "Model for \"#{prefix}\" not found"
end

.finder(eid) ⇒ Object



70
71
72
73
74
75
# File 'lib/exid/record.rb', line 70

def self.finder(eid)
  Coder.decode(eid) => prefix, value

  mod = find_module(prefix)
  mod.klass.where(mod.field => value)
end

.register_module(entry) ⇒ Object

When app is eager loaded in production, all models are loaded and registered. This logic with delte and readd is for development purpose, to make sure we can make changes to the app and have this logic working at the same time. We only use prefix as identify for the set elements.



46
47
48
49
50
51
# File 'lib/exid/record.rb', line 46

def self.register_module(entry)
  MUTEX.synchronize do
    @registered_modules.delete(entry)
    @registered_modules.add(entry)
  end
end

.registered_modulesObject



59
60
61
62
63
# File 'lib/exid/record.rb', line 59

def self.registered_modules
  MUTEX.synchronize do
    @registered_modules.dup
  end
end

.unloadObject



53
54
55
56
57
# File 'lib/exid/record.rb', line 53

def self.unload
  MUTEX.synchronize do
    @registered_modules = Set.new
  end
end

Instance Method Details

#included(base) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/exid/record.rb', line 16

def included(base)
  base.public_send(:include, @module_value)
  base.public_send(:include, @module_shared)
  base.public_send(:extend, @module_shared)
  base.public_send(:extend, @module_static)

  self.class.register_module(
    Entry.new(
      prefix: base.exid_prefix_name,
      field: base.exid_field,
      klass: base
    )
  )
end