Skip to content

Instantly share code, notes, and snippets.

@munckymagik
Created August 31, 2019 06:59
Show Gist options
  • Save munckymagik/30ca7afc535dd340e118311756f1f154 to your computer and use it in GitHub Desktop.
Save munckymagik/30ca7afc535dd340e118311756f1f154 to your computer and use it in GitHub Desktop.
Ruby module_functions demo
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