Created
April 25, 2014 16:14
-
-
Save yaodong/11294892 to your computer and use it in GitHub Desktop.
How to define and include 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
# module name is a constant | |
module Debug | |
# constant will not be mixin | |
LEVEL = 'error' | |
# instance variable. | |
# It may clash with those of the host class or with those of other mixins. | |
# For the most part, mixin doesn't use instance variables directly, they use accessors of hosts. | |
attr_accessor :message | |
# instance method | |
def whois | |
#{self.class.name}" | |
end | |
end | |
class Apple | |
# mixin a module use `include` | |
include Debug | |
end | |
apple = Apple.new | |
# access mixin method | |
p apple.whois #=> Apple | |
# access mixin instance variable | |
# Again, a module has its own state is not a mixin, it should be written as a class. | |
apple.message = 'Google' | |
p apple.message #=> Apple |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment