diff options
author | Adam <adam@adambard.com> | 2013-09-08 21:52:54 -0700 |
---|---|---|
committer | Adam <adam@adambard.com> | 2013-09-08 21:52:54 -0700 |
commit | 6172fee1a4a44d53648a26cd7764de9fcea46313 (patch) | |
tree | bfb1264276f5d60713e2f9a760672076115faf51 /ruby.html.markdown | |
parent | a933d419e07fd8af6effa89200b581e904c61679 (diff) | |
parent | 599ed0df3012ae578281dd92afc5a48891f56810 (diff) |
Merge branch 'master' of https://github.com/adambard/learnxinyminutes-docs
Diffstat (limited to 'ruby.html.markdown')
-rw-r--r-- | ruby.html.markdown | 51 |
1 files changed, 51 insertions, 0 deletions
diff --git a/ruby.html.markdown b/ruby.html.markdown index 80682682..b9ba83cb 100644 --- a/ruby.html.markdown +++ b/ruby.html.markdown @@ -403,4 +403,55 @@ end Human.bar # 0 Doctor.bar # nil +module ModuleExample + def foo + 'foo' + end +end + +# Including modules binds the methods to the object instance +# Extending modules binds the methods to the class instance + +class Person + include ModuleExample +end + +class Book + extend ModuleExample +end + +Person.foo # => NoMethodError: undefined method `foo' for Person:Class +Person.new.foo # => 'foo' +Book.foo # => 'foo' +Book.new.foo # => NoMethodError: undefined method `foo' + +# Callbacks when including and extending a module are executed + +module ConcernExample + def self.included(base) + base.extend(ClassMethods) + base.send(:include, InstanceMethods) + end + + module ClassMethods + def bar + 'bar' + end + end + + module InstanceMethods + def qux + 'qux' + end + end +end + +class Something + include ConcernExample +end + +Something.bar # => 'bar' +Something.qux # => NoMethodError: undefined method `qux' +Something.new.bar # => NoMethodError: undefined method `bar' +Something.new.qux # => 'qux' ``` |