Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
module Foo1
def self.bar
"Yolo"
end
end
"Foo1.bar => #{Foo1.bar}" # => "Foo1.bar => Yolo"
module Foo2
def bar # !> previous definition of bar was here
"Yolo"
end
extend self
end
# extend self
"Foo2.bar => #{Foo2.bar}" # => "Foo2.bar => Yolo"
object = Object.new
object.extend(Foo2)
"object extended bar: #{object.bar}" # => "object extended bar: Yolo"
module Foo2
def bar # !> method redefined; discarding old bar
"altered Yolo"
end
end
# altering def bar
"Foo2.bar => #{Foo2.bar}" # => "Foo2.bar => altered Yolo"
object = Object.new
object.extend(Foo2)
"object extended bar: #{object.bar}" # => "object extended bar: altered Yolo"
module Foo3
def bar
"Yolo"
end
module_function :bar
end
# module_function :bar
"Foo3.bar => #{Foo3.bar}" # => "Foo3.bar => Yolo"
object = Object.new
object.extend(Foo3)
# "object extended bar: #{object.bar}" # => private method `bar' called for #<Object:0x007fab199590e0> (NoMethodError)
class Calling
include Foo3
def call_bar
bar
end
end
# include with module_function
"Foo3.bar => #{Foo3.bar}" # => "Foo3.bar => Yolo"
object = Calling.new
"object extended call_bar: #{object.call_bar}" # => "object extended call_bar: Yolo"
module Foo3
def bar
"altered instance Yolo"
end
end
# altering def bar which is a module_function
"Foo3.bar => #{Foo3.bar} (remains the same)" # => "Foo3.bar => Yolo (remains the same)"
object = Object.new
object.extend(Foo3)
"object extended bar: #{object.bar}" # => "object extended bar: altered instance Yolo"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment