Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save etiennebarrie/8da01739172209fc61483dc7a8296dc4 to your computer and use it in GitHub Desktop.
Save etiennebarrie/8da01739172209fc61483dc7a8296dc4 to your computer and use it in GitHub Desktop.
# Defining private methods is less clean using module_function
module ExtendSelf
extend self
def bar
foo
end
private
def foo
42
end
end
module ModuleFunction
module_function
def bar
foo
end
def foo
42
end
private_class_method :foo
end
def fails
yield
fail Exception, "should have failed"
rescue => e
p e
end
p ExtendSelf.bar
fails { ExtendSelf.foo }
p ModuleFunction.bar
fails { ModuleFunction.foo }
puts '='*80
# module_function copies methods, and as such can break metaprogramming
module Bigger
def bigger(name)
method = method(name)
define_method(name) { method.call + 1 }
end
end
module ExtendSelf
extend Bigger
bigger :foo
end
module ModuleFunction
extend Bigger
bigger :foo
end
p ExtendSelf.bar
p ModuleFunction.bar
puts '='*80
# class << self changes constant lookup
module ConstantDefiningModule
CONSTANT = 42
PRIVATE_CONSTANT = 42
private_constant :PRIVATE_CONSTANT
end
module ExtendSelf
include ConstantDefiningModule
def constant_lookup
CONSTANT
end
def private_constant_lookup
PRIVATE_CONSTANT
end
end
module ModuleFunction
include ConstantDefiningModule
module_function
def constant_lookup
CONSTANT
end
def private_constant_lookup
PRIVATE_CONSTANT
end
end
module ClassSelfChild
include ConstantDefiningModule
class << self
def constant_lookup
CONSTANT
end
def private_constant_lookup
PRIVATE_CONSTANT
end
def constant_lookup_on_self
self::CONSTANT
end
def private_constant_lookup_on_self
self::PRIVATE_CONSTANT
end
end
def self.def_self_constant_lookup
CONSTANT
end
def self.private_def_self_constant_lookup
PRIVATE_CONSTANT
end
end
p ExtendSelf.constant_lookup
p ModuleFunction.constant_lookup
fails { ClassSelfChild.constant_lookup }
p ClassSelfChild.def_self_constant_lookup
p ClassSelfChild.constant_lookup_on_self
p ClassSelfChild.private_def_self_constant_lookup
fails { ClassSelfChild.private_constant_lookup }
fails { ClassSelfChild.private_constant_lookup_on_self }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment