Skip to content

Commit

Permalink
WIP: specific error when calling DiscourseEvent.on outside of `plug…
Browse files Browse the repository at this point in the history
…in.rb`
  • Loading branch information
Flink committed Feb 7, 2024
1 parent f3c9c93 commit c1ebfa4
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 8 deletions.
11 changes: 10 additions & 1 deletion lib/rubocop/cop/discourse/plugins/discourse_event.rb
Expand Up @@ -7,6 +7,8 @@ module Plugins
class DiscourseEvent < Base
MSG =
"Use `on` instead of `DiscourseEvent.on` as the latter will listen to events even if the plugin is disabled."
NOT_OUTSIDE_PLUGIN_RB =
"Don’t call `DiscourseEvent.on` outside of `plugin.rb`."
RESTRICT_ON_SEND = [:on].freeze

def_node_matcher :discourse_event_on?, <<~MATCHER
Expand All @@ -15,7 +17,14 @@ class DiscourseEvent < Base

def on_send(node)
return unless discourse_event_on?(node)
add_offense(node, message: MSG)
return add_offense(node, message: MSG) if in_plugin_rb_file?
add_offense(node, message: NOT_OUTSIDE_PLUGIN_RB)
end

private

def in_plugin_rb_file?
processed_source.path.split("/").last == "plugin.rb"
end
end
end
Expand Down
27 changes: 20 additions & 7 deletions spec/lib/rubocop/cop/plugins/discourse_event_spec.rb
Expand Up @@ -7,20 +7,33 @@

let(:config) { RuboCop::Config.new }

context "when `DiscourseEvent.on` is called" do
it "registers an offense" do
expect_offense(<<~RUBY)
context "when outside `plugin.rb`" do
context "when `DiscourseEvent.on` is called" do
it "registers an offense" do
expect_offense(<<~RUBY, "another_file.rb")
DiscourseEvent.on(:topic_status_updated) { do_something }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Discourse/Plugins/DiscourseEvent: Don’t call `DiscourseEvent.on` outside of `plugin.rb`.
RUBY
end
end
end

context "when inside `plugin.rb`" do
context "when `DiscourseEvent.on` is called" do
it "registers an offense" do
expect_offense(<<~RUBY, "plugin.rb")
DiscourseEvent.on(:topic_status_updated) { do_something }
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ Discourse/Plugins/DiscourseEvent: Use `on` instead of `DiscourseEvent.on` [...]
RUBY
end
end
end

context "when `on` is called" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY)
context "when `on` is called" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY, "plugin.rb")
on(:topic_status_updated) { do_something }
RUBY
end
end
end
end

0 comments on commit c1ebfa4

Please sign in to comment.