Rubocop: Proper cop/message is required for lint useless-access-modifier cop if only class methods are defined

Created on 5 Oct 2014  路  1Comment  路  Source: rubocop-hq/rubocop

Suppose we have a file with following code in it.

class Sample
  def method_a
    puts 'This is Method A'
  end

  private

  def self.test_method
    puts 'this is test method'
  end

  def self.private_method_a
    puts 'this is private method a'
  end
end

If we run rubocop -l over it,

Offenses:

sample-rubocop-check.rb:6:2: W: Useless private access modifier.
    private
 ^^^^^^^

1 file inspected, 1 offense detected

The error is given if no instance method is defined after private access modifier.
But as all methods are self (class) methods after the modifier - the cop should identify this and give proper message of using private_class_method in this case.

Most helpful comment

Just to be clear, private and private_class_method aren鈥檛 equivalent. Calling private without arguments changes the scope of the class, so following method definitions are declared private. Calling private_class_method without arguments doesn鈥檛 do anything (I think).

In your example, you would need to call either

private_class_method :test_method
private_class_method :private_method_a

or (in Ruby >= 2.1)

class Sample
  def method_a
    puts 'This is Method A'
  end

  private_class_method def self.test_method
    puts 'this is test method'
  end

  private_class_method def self.private_method_a
    puts 'this is private method a'
  end
end

The style guide doesn鈥檛 explicitly recommend one style over another, but I would go with the class << self syntax:

class Sample
  def method_a
    puts 'This is Method A'
  end

  class << self
    private

    def test_method
      puts 'this is test method'
    end

    def private_method_a
      puts 'this is private method a'
    end
  end
end

>All comments

Just to be clear, private and private_class_method aren鈥檛 equivalent. Calling private without arguments changes the scope of the class, so following method definitions are declared private. Calling private_class_method without arguments doesn鈥檛 do anything (I think).

In your example, you would need to call either

private_class_method :test_method
private_class_method :private_method_a

or (in Ruby >= 2.1)

class Sample
  def method_a
    puts 'This is Method A'
  end

  private_class_method def self.test_method
    puts 'this is test method'
  end

  private_class_method def self.private_method_a
    puts 'this is private method a'
  end
end

The style guide doesn鈥檛 explicitly recommend one style over another, but I would go with the class << self syntax:

class Sample
  def method_a
    puts 'This is Method A'
  end

  class << self
    private

    def test_method
      puts 'this is test method'
    end

    def private_method_a
      puts 'this is private method a'
    end
  end
end
Was this page helpful?
0 / 5 - 0 ratings