Created
August 31, 2019 06:59
-
-
Save munckymagik/30ca7afc535dd340e118311756f1f154 to your computer and use it in GitHub Desktop.
Ruby module_functions demo
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
module A | |
module_function | |
def a | |
'I am a' | |
end | |
def b | |
'I am b' | |
end | |
end | |
# module_function provides an easy way to define functions with the module as a receiver | |
# No need for `extend ClassMethods` or reopening classes | |
puts A.a | |
puts A.b | |
class C | |
# Including a module that has functions defined with module_function _copies_ them in as private | |
# instance methods | |
include A | |
end | |
puts C.respond_to? :a | |
puts C.respond_to? :b | |
c = C.new | |
puts c.respond_to? :a | |
puts c.respond_to? :b | |
puts c.send(:a) | |
puts c.send(:b) | |
class D | |
# Extending a module that has functions defined with module_function | |
extend A | |
end | |
puts D.respond_to? :a | |
puts D.respond_to? :b | |
puts D.send(:a) | |
puts D.send(:b) | |
d = D.new | |
puts d.respond_to? :a | |
puts d.respond_to? :b |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment