Skip to content

Instantly share code, notes, and snippets.

@danini-the-panini
Created August 23, 2023 07:54
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 danini-the-panini/7d975d051de36a885331967f18f70fa9 to your computer and use it in GitHub Desktop.
Save danini-the-panini/7d975d051de36a885331967f18f70fa9 to your computer and use it in GitHub Desktop.
Ruby Private and Protected examples
class Foo
def call_foo
foo
end
def call_self_foo
self.foo
end
def call_other_foo(other)
other.foo
end
private # <-- change this to protected and see what changes
def foo
puts 'Foo#foo got called'
end
end
class Bar < Foo
def bar_call_foo
foo
end
def bar_call_self_foo
self.foo
end
def bar_call_other_foo(other)
other.foo
end
end
class NotFoo
protected
def foo
puts 'NotFoo#foo got called'
end
end
Foo.new.call_foo
Foo.new.call_self_foo
Foo.new.call_other_foo(Foo.new) rescue puts $!.message
Foo.new.call_other_foo(Bar.new) rescue puts $!.message
Foo.new.call_other_foo(NotFoo.new) rescue puts $!.message
Bar.new.call_foo
Bar.new.call_self_foo
Bar.new.call_other_foo(Foo.new) rescue puts $!.message
Bar.new.call_other_foo(Bar.new) rescue puts $!.message
Bar.new.call_other_foo(NotFoo.new) rescue puts $!.message
module Foo
def call_foo
foo
end
def call_self_foo
self.foo
end
def call_other_foo(other)
other.foo
end
private # <-- change this to protected and see what changes
def foo
puts 'Foo#foo got called'
end
end
class Bar
include Foo
def bar_call_foo
foo
end
def bar_call_self_foo
self.foo
end
def bar_call_other_foo(other)
other.foo
end
end
class NotFoo
protected
def foo
puts 'NotFoo#foo got called'
end
end
Bar.new.call_foo
Bar.new.call_self_foo
Bar.new.call_other_foo(Bar.new) rescue puts $!.message
Bar.new.call_other_foo(NotFoo.new) rescue puts $!.message
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment