Skip to content

Instantly share code, notes, and snippets.

@yaodong
Created April 25, 2014 16:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yaodong/11294892 to your computer and use it in GitHub Desktop.
Save yaodong/11294892 to your computer and use it in GitHub Desktop.
How to define and include a module
# 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