Skip to content

Instantly share code, notes, and snippets.

@science
Last active August 29, 2015 14:12
Show Gist options
  • Save science/331b3a88512c6e467bfa to your computer and use it in GitHub Desktop.
Save science/331b3a88512c6e467bfa to your computer and use it in GitHub Desktop.
How to "include" Instance and Class methods into a class in ruby
module Lib
# this loads our class methods when called by "include"
def self.included(base)
base.extend(ClassMethods)
# code here will run when lib is imported, in Lib module context
puts "Lib context: #{self.to_s}"
# this calls the lib_init method to run any class set up code
base.send(:lib_init)
end
module ClassMethods
def lib_init
# code here will run when library is imported, in class context
puts "Class context: #{self.to_s}"
end
def class_method
puts "class method here"
end
end
def instance_method
puts "instance method here"
end
end
class MyClass
puts "Including Lib now.."
include Lib
end
# Including Lib now..
# Lib context: Lib
# Class context: MyClass
MyClass.class_method
# class method here
myclass = MyClass.new
myclass.instance_method
# "instance method here"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment