Last Updated: February 25, 2016
·
1K
· ready4god2513

Understand Ruby Visibility

A part of Ruby that has come back to bite many developers (and even worse those that are not writing tests (for shame)) is its handling of visibility- public, protected and private. So I wanted to break it down a bit with a concrete example (Ruby 2.1.2)-

 class Person

  def apublic
    puts "I am public"
  end

  def instance_check_protected(i)
    i.aprotected
  end

  def instance_check_private(i)
    i.aprivate
  end

  def call_protected_self
    self.aprotected
  end

  def implicit_protected
    aprotected
  end

  def call_private_self
    self.aprivate
  end

  def implicit_private
    aprivate
  end

  protected def aprotected
    puts "I am protected"
  end

  private def aprivate
    puts "I am private"
  end

end

Now our class is all set up, let's try it out.

p = Person.new

p.apublic # I am public
p.aprotected # protected method `aprotected' called for #<Person:0x007ffafaa175f0> (NoMethodError)
p.aprivate # private method `aprivate' called for #<Person:0x007fec208ef670> (NoMethodError)

p.send(:aprotected) # I am protected
p.method(:aprotected).call  # I am protected

p.send(:aprivate)  # I am private
p.method(:aprivate).call  # I am private

p.call_protected_self  # I am protected
p.implicit_protected  # I am protected

p.instance_check_protected(Person.new) # I am protected
p.instance_check_private(Person.new) # private method `aprivate' called for #<Person:0x007fbf98a2f2d8> (NoMethodError)

p.call_private_self # private method `aprivate' called for #<Person:0x007f8d6a8976b0> (NoMethodError)
p.implicit_private  # I am private