Skip to content

Commit

Permalink
WIP: add cop to namespace methods
Browse files Browse the repository at this point in the history
  • Loading branch information
Flink committed Feb 8, 2024
1 parent f36eee8 commit 422fece
Show file tree
Hide file tree
Showing 3 changed files with 113 additions and 0 deletions.
3 changes: 3 additions & 0 deletions config/default.yml
Expand Up @@ -70,3 +70,6 @@ Discourse/Plugins/CallRequiresPlugin:

Discourse/Plugins/DiscourseEvent:
Enabled: true

Discourse/Plugins/NamespaceMethods:
Enabled: true
24 changes: 24 additions & 0 deletions lib/rubocop/cop/discourse/plugins/namespace_methods.rb
@@ -0,0 +1,24 @@
# frozen_string_literal: true

module RuboCop
module Cop
module Discourse
module Plugins
class NamespaceMethods < Base
MSG = "Don’t define methods outside a class or a module."

def on_def(node)
return if inside_namespace?(node)
add_offense(node, message: MSG)
end

private

def inside_namespace?(node)
node.each_ancestor.detect { _1.class_type? || _1.module_type? }
end
end
end
end
end
end
86 changes: 86 additions & 0 deletions spec/lib/rubocop/cop/plugins/namespace_methods_spec.rb
@@ -0,0 +1,86 @@
# frozen_string_literal: true

require "spec_helper"

RSpec.describe RuboCop::Cop::Discourse::Plugins::NamespaceMethods, :config do
subject(:cop) { described_class.new(config) }

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

context "when defining a method outside any namespace" do
it "registers an offense" do
expect_offense(<<~RUBY)
def my_method
^^^^^^^^^^^^^ Discourse/Plugins/NamespaceMethods: Don’t define methods outside a class or a module.
"my_value"
end
class MyClass
def my_method
"my_method"
end
end
RUBY
end
end

context "when defining a method inside a class" do
context "when defining an instance method" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY)
class MyClass
def my_method
"my_value"
end
end
RUBY
end
end

context "when defining a class method" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY)
class MyClass
class << self
def my_method
"my_value"
end
def another_method
"plop"
end
end
end
RUBY
end
end
end

context "when defining a method inside a module" do
context "when defining an instance method" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY)
module MyModule
def my_method
"my_value"
end
end
RUBY
end
end

context "when defining a class method" do
it "does not register an offense" do
expect_no_offenses(<<~RUBY)
module MyModule
class << self
def my_method
"my_value"
end
end
end
RUBY
end
end
end
end

0 comments on commit 422fece

Please sign in to comment.