Search code examples
rubyprivateprotectedruby-2.1

Can the Ruby 2.1 shorthand for private/protected be used for class methods?


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?


Solution

  • 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