90 likes | 222 Vues
Ruby modules are named groups of methods, constants, and class variables but cannot be instantiated or subclassed. They serve as namespaces and mixins, allowing the definition of utility functions that do not require an object instance. This guide explores the purpose and functionality of modules, including examples with Base64 encoding and mixing instance methods into classes. We'll also compare modules to interfaces in Java, examine best practices, and discuss the Liskov Substitution Principle in relation to Ruby's flexible class behavior.
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)