-
-
Save bertomartin/4741340 to your computer and use it in GitHub Desktop.
This file contains 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
# here's option one - standard way to add class methods and instance methods from a module into a class | |
module MyParent | |
# callback which is called on inclusion | |
def self.included(klass) | |
klass.extend(ClassMethods) | |
klass.send(:include, InstanceMethods) | |
end | |
# These are class methods added to klass | |
module ClassMethods | |
def a_class_method | |
puts "although technically it's an eigenclass mehod ;)" | |
end | |
end | |
# These are instance methods added to klass | |
module InstanceMethods | |
def an_instance_method | |
puts "Im an instance method" | |
end | |
end | |
end | |
# In this case - nothing is reported | |
class MyClass | |
# tell me when a method is defined on MyClass | |
def self.method_added(method) | |
puts "#{method} was defined" | |
end | |
include MyParent | |
end | |
# ============================== | |
# = Or... we have this option: = | |
# ============================== | |
# here's option two - on including the module, define these methods on the Class itself | |
module MyParent2 | |
# callback which is called on inclusion | |
def self.included(klass) | |
# change scope to within klass | |
klass.class_eval do | |
# define our class method on klass | |
def self.a_class_method | |
puts "although technically it's an eigenclass mehod ;)" | |
end | |
# define our instance method on klass | |
def an_instance_method | |
puts "Im an instance method" | |
end | |
end | |
end | |
end | |
# In this case - nothing is reported | |
class MyClass2 | |
# tell me when a method is defined on MyClass | |
def self.method_added(method) | |
puts "#{method} was defined" | |
end | |
include MyParent2 | |
end | |
# is this method available to MyClass? | |
puts MyClass.instance_methods.include?(:an_instance_method) | |
# is this method available to MyClass2 ? | |
puts MyClass2.instance_methods.include?(:an_instance_method) | |
# is this method defined in MyClass? | |
puts MyClass.instance_methods(false).include?(:an_instance_method) | |
# is this method defined in MyClass2? | |
puts MyClass2.instance_methods(false).include?(:an_instance_method) | |
# ========== | |
# = Notes: = | |
# ========== | |
# It looks to me like in the 2nd option, the instance method is being defined in the class, rather | |
# than simply being available to it. | |
# When I benchmark these (using thousands of instances), option 2 takes longer | |
# | |
# I *believe* option 2 requires more memory than option 1 because several instances of the method are | |
# being created rather than just one |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment