mirror of
https://github.com/discourse/discourse.git
synced 2025-04-09 01:00:52 +08:00
FEATURE: Allow options to be set when adding model callbacks.
This commit is contained in:
parent
2d0c99636a
commit
3909f342f6
@ -112,7 +112,7 @@ class Plugin::Instance
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
def add_model_callback(klass, callback, &block)
|
def add_model_callback(klass, callback, options = {}, &block)
|
||||||
klass = klass.to_s.classify.constantize rescue klass.to_s.constantize
|
klass = klass.to_s.classify.constantize rescue klass.to_s.constantize
|
||||||
plugin = self
|
plugin = self
|
||||||
|
|
||||||
@ -122,10 +122,11 @@ class Plugin::Instance
|
|||||||
hidden_method_name = :"#{method_name}_without_enable_check"
|
hidden_method_name = :"#{method_name}_without_enable_check"
|
||||||
klass.send(:define_method, hidden_method_name, &block)
|
klass.send(:define_method, hidden_method_name, &block)
|
||||||
|
|
||||||
klass.send(callback) do |*args|
|
klass.send(callback, options) do |*args|
|
||||||
send(hidden_method_name, *args) if plugin.enabled?
|
send(hidden_method_name, *args) if plugin.enabled?
|
||||||
end
|
end
|
||||||
|
|
||||||
|
hidden_method_name
|
||||||
end
|
end
|
||||||
|
|
||||||
# Add validation method but check that the plugin is enabled
|
# Add validation method but check that the plugin is enabled
|
||||||
|
@ -191,4 +191,49 @@ describe Plugin::Instance do
|
|||||||
end
|
end
|
||||||
end
|
end
|
||||||
|
|
||||||
|
describe '#add_model_callback' do
|
||||||
|
let(:metadata) do
|
||||||
|
metadata = Plugin::Metadata.new
|
||||||
|
metadata.name = 'test'
|
||||||
|
metadata
|
||||||
|
end
|
||||||
|
|
||||||
|
let(:plugin_instance) do
|
||||||
|
plugin = Plugin::Instance.new(nil, "/tmp/test.rb")
|
||||||
|
plugin.metadata = metadata
|
||||||
|
plugin
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'should add the right callback' do
|
||||||
|
called = 0
|
||||||
|
|
||||||
|
method_name = plugin_instance.add_model_callback(User, :after_create) do
|
||||||
|
called += 1
|
||||||
|
end
|
||||||
|
|
||||||
|
user = Fabricate(:user)
|
||||||
|
|
||||||
|
expect(called).to eq(1)
|
||||||
|
|
||||||
|
user.update_attributes!(username: 'some_username')
|
||||||
|
|
||||||
|
expect(called).to eq(1)
|
||||||
|
end
|
||||||
|
|
||||||
|
it 'should add the right callback with options' do
|
||||||
|
called = 0
|
||||||
|
|
||||||
|
method_name = plugin_instance.add_model_callback(User, :after_commit, on: :create) do
|
||||||
|
called += 1
|
||||||
|
end
|
||||||
|
|
||||||
|
user = Fabricate(:user)
|
||||||
|
|
||||||
|
expect(called).to eq(1)
|
||||||
|
|
||||||
|
user.update_attributes!(username: 'some_username')
|
||||||
|
|
||||||
|
expect(called).to eq(1)
|
||||||
|
end
|
||||||
|
end
|
||||||
end
|
end
|
||||||
|
Loading…
x
Reference in New Issue
Block a user