summaryrefslogtreecommitdiffhomepage
path: root/ruby.html.markdown
diff options
context:
space:
mode:
authorMatthew Johnston <warmwaffles@gmail.com>2013-09-08 11:46:08 -0500
committerMatthew Johnston <warmwaffles@gmail.com>2013-09-08 11:46:08 -0500
commit9cc1982c484e99adfb922733cb9c0fb5768b6a77 (patch)
treef861de4c4c52b7c48f6608cd41618e0da0e98c74 /ruby.html.markdown
parent5a87423e209ee77b53e20f70ccc87c26511c4869 (diff)
Added module extension and inclusion examples
Also added examples for callbacks made when modules are included and extended.
Diffstat (limited to 'ruby.html.markdown')
-rw-r--r--ruby.html.markdown51
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'
```