Skip to content

Instantly share code, notes, and snippets.

@lucianghinda
Created August 31, 2022 04:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucianghinda/8c6ee0d29005d0ecc8eb5ad2620e7833 to your computer and use it in GitHub Desktop.
Save lucianghinda/8c6ee0d29005d0ecc8eb5ad2620e7833 to your computer and use it in GitHub Desktop.
# Code Summary
# 📖 https://paweldabrowski.com/articles/public-private-and-protected-in-ruby
# Part 1/5: Common way of defining private methods
class Person
def name; end
private
def age; end
end
# Passing arguments to private
class Person
def age; end
private :age
end
# Passing method definition to private
class Person
private def age
puts "I'm private"
end
end
# Part 2/5: Protected methods
class Employee
protected
def my_protected_method; end
end
class Employee
protected def my_protected_method; end
end
Employee.new.my_protected_method # raises NoMethodError
class Director
def call(employee)
employee.my_protected_method
end
end
Director.new.call(Employee.new) #will work
# Part 3/5: Calling private or protected methods
class Employee
def my_public_method; end
private
end
# using `send`
# - will work for calling any method
# - ⚠️ can be redefined
Employee.new.send(:any_method)
# using `public_send`
# will only call public method, will not work on private or protected
Employee.new.public_send(:my_public_method)
# using `__send__`
# - use this instead of `send`
# - __send__ will show a warning when redefined
Employee.new.__send__(:any_method)
# Part 4/5: Private Class Methods
# ❌ The following will NOT work
class Employee
private
def self.call; end
end
# ✅ This will work:
class Employee
class << self
private
def call; end
end
end
# ✅ Or this will work:
class Employee
def self.call; end
private_class_method :call
end
# ✅ This will also work
class Employee
private_class_method def self.call; end
end
# Part 5/5: Constants and attributes
# As they are defined in the class
# Constants
## ❌ The following will NOT work
class Employee
private
MY_CONSTANT = 1
end
## ✅ This will work
class Employee
MY_CONSTANT = 1
private_constant :MY_CONSTANT
end
# You can define attr_accessor as private
## Only from Ruby 3+
class Employee
private attr_accessor :name, :age
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment