MaxGabriel
MaxGabriel

Reputation: 7705

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?

Upvotes: 0

Views: 337

Answers (2)

matt
matt

Reputation: 79783

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

Upvotes: 4

Nikita Chernov
Nikita Chernov

Reputation: 2061

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.

Upvotes: 5

Related Questions