90 likes | 215 Views
Ruby Modules etc. and other languages… . Modules . A module is a named group of methods, constants, and class variables All classes are modules Modules are not classes Can’t be instantiated Can’t be subclassed Purpose: namespaces and mixins. Namespace. Remember namespaces from C++?.
E N D
Ruby Modules etc. and other languages…
Modules • A module is a named group of methods, constants, and class variables • All classes are modules • Modules are not classes • Can’t be instantiated • Can’t be subclassed • Purpose: namespaces and mixins
Namespace Remember namespaces from C++? Example: want to provide utility functions that don’t require an object. Maybe encode/decode functions, conversions, math functions, etc. Can add global methods, but then need to worry about naming conflicts.
Example from text module Base64 def self.encode (data) end def self.decode (text) #could be: Base64.decode # cannot leave off self end end • Call as: text = Base64.encode(data) data = Base64.decode(text)
Mixins QuickEx: • If a module defines instance methods, those can be “mixed into” other classes • Essentially eliminates need for multiple inheritance • Examples: • Enumerable. defines iterators that make use of each method • Comparable. defines comparison operators (<, <=,==, >, >=, between?) in terms of <=> (like compareTo) • Module.include function does the “mixing”
Mixin Best Practices • Quick Exercise: take a look at: • http://stackoverflow.com/questions/575920/is-a-ruby-module-equivalent-to-a-java-interface • http://matt.aimonetti.net/posts/2012/07/30/ruby-class-module-mixins/ • http://blade.nagaokaut.ac.jp/cgi-bin/scat.rb/ruby/ruby-talk/16071
require vs include • require brings in the contents of another file (like “include” in C++) • include “mixes in” a module module FlyingCreature def Fly end end class Bird include FlyingCreature #... end class Bat < Mammal include FlyingCreature #... end dracula = Bat.new Notice that dracula.is_a? Mammal is true, and so is dracula.is_a? FlyingCreature.
Singleton Method Example From: http://www.slideshare.net/ShugoMaeda/rc2010-refinements matz = Person.new def matz.design_ruby end shugo = Person.new shugo.design_ruby => no method error
Liskov Substitution Principle From: http://www.slideshare.net/ShugoMaeda/rc2010-refinements • LSP: instances of a class after reopen must behave like instances of a class before • Violation: p 1/2 => 0 require "mathn" p 1/2 => (1/2)