0

In Ruby 2.1, def now returns a symbol

[1] pry(main)> def foo; end
=> :foo

One cool use case of this is that because private and protected are methods that take a symbol and make the method private, you can now create a private method like so:

private def foo
end

However, I can't get this to work with class methods. This code:

protected def self.baz
end

will error with: protected': undefined method 'baz' for class 'User' (NameError)".

Is there a way to get that working?

MaxGabriel
  • 7,617
  • 4
  • 35
  • 82

2 Answers2

5

You can achieve that by using singleton class of your class:

class Foo
  def self.baz
    ...
  end

  class << self
    private :baz
  end
end

or in a single attempt:

class Foo
  class << self
    private def baz
      ...
    end
  end
end

So, everything executed in a class << self block will be applied on a class level. Resulting in a private/protected class methods.

Nikita Chernov
  • 2,031
  • 16
  • 13
4

private is a method used to mark instance methods as private. The equivalent for class methods is private_class_method so the equivalent idiom would be the somewhat unwieldy and redundant:

private_class_method def self.foo
  #...
end
matt
  • 78,533
  • 8
  • 163
  • 197