Created
May 7, 2014 21:06
-
-
Save BuddyLReno/f82577daf57eb14b373d to your computer and use it in GitHub Desktop.
Ruby: Include instance and class methods in a module.
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
# using include to include both class methods and instance methods | |
# http://www.railstips.org/blog/archives/2009/05/15/include-vs-extend-in-ruby/ | |
module Foo | |
def self.included(base) | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def bar | |
puts 'class method' | |
end | |
end | |
def foo | |
puts 'instance method' | |
end | |
end | |
class Baz | |
include Foo | |
end | |
Baz.bar # class method | |
Baz.new.foo # instance method | |
Baz.foo # NoMethodError: undefined method ‘foo’ for Baz:Class | |
Baz.new.bar # NoMethodError: undefined method ‘bar’ for #<Baz:0x1e3d4> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment