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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
# File 'lib/trackstamps/base.rb', line 19
def self.construct_new_module(module_key)
mod = Module.new
mod.define_singleton_method(:inspect) do
"Trackstamps::Reborn[:#{module_key}]"
end
mod.define_method(:trackstamps_module) do
mod
end
mod.define_singleton_method(:[]) do |key|
Trackstamps::Base[key]
end
mod.module_eval do
extend Dry::Configurable
extend ActiveSupport::Concern
autoload :VERSION, "trackstamps/reborn/version"
const_set(:Current, Trackstamps::Base::Current)
setting :get_current_user, default: -> { Current.user }
setting :user_class_name, default: "User".freeze
setting :updater_foreign_key, default: "updated_by_id".freeze
setting :creator_foreign_key, default: "created_by_id".freeze
included do
def trackstamps_current_user
trackstamps_module.config.get_current_user.call
end
private :trackstamps_module
private :trackstamps_current_user
before_save :trackstamps_set_updater
before_create :trackstamps_set_creator
const_set(
:UPDATER_FOREIGN_KEY,
mod.config.updater_foreign_key.dup.freeze
)
const_set(
:CREATOR_FOREIGN_KEY,
mod.config.creator_foreign_key.dup.freeze
)
private_constant :UPDATER_FOREIGN_KEY
private_constant :CREATOR_FOREIGN_KEY
belongs_to :updater,
class_name: mod.config.user_class_name,
foreign_key: const_get(:UPDATER_FOREIGN_KEY),
optional: true
belongs_to :creator,
class_name: mod.config.user_class_name,
foreign_key: const_get(:CREATOR_FOREIGN_KEY),
optional: true
def trackstamps_set_updater
return unless trackstamps_current_user
send(:"#{self.class.const_get(:UPDATER_FOREIGN_KEY)}=", trackstamps_current_user.id)
end
def trackstamps_set_creator
return unless trackstamps_current_user
send(:"#{self.class.const_get(:CREATOR_FOREIGN_KEY)}=", trackstamps_current_user.id)
end
end
class_methods do
def with_trackstamps
includes(:creator, :updater)
end
end
end
mod
end
|