Created
August 31, 2022 04:20
-
-
Save lucianghinda/8c6ee0d29005d0ecc8eb5ad2620e7833 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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