Slide 1

Slide 1 text

MODULE MAGIC and my trip to RubyKaigi2009

Slide 2

Slide 2 text

JAMES EDWARD GRAY II

Slide 3

Slide 3 text

JAMES EDWARD GRAY II Created the Ruby Quiz and wrote that book

Slide 4

Slide 4 text

JAMES EDWARD GRAY II Created the Ruby Quiz and wrote that book Built FasterCSV (now CSV), HighLine (with Greg), Elif, and some other scarier experiments

Slide 5

Slide 5 text

JAMES EDWARD GRAY II Created the Ruby Quiz and wrote that book Built FasterCSV (now CSV), HighLine (with Greg), Elif, and some other scarier experiments Documented some of Ruby

Slide 6

Slide 6 text

JAMES EDWARD GRAY II Created the Ruby Quiz and wrote that book Built FasterCSV (now CSV), HighLine (with Greg), Elif, and some other scarier experiments Documented some of Ruby http://blog.grayproductions.net/

Slide 7

Slide 7 text

JAMES EDWARD GRAY II Created the Ruby Quiz and wrote that book Built FasterCSV (now CSV), HighLine (with Greg), Elif, and some other scarier experiments Documented some of Ruby http://blog.grayproductions.net/ http://twitter.com/JEG2

Slide 8

Slide 8 text

LSRC SPEECHES TV shows geeks should know!

Slide 9

Slide 9 text

LSRC SPEECHES TV shows geeks should know!

Slide 10

Slide 10 text

RUBYKAIGI2009

Slide 11

Slide 11 text

RUBYKAIGI2009

Slide 12

Slide 12 text

RUBYKAIGI2009 See how the Japanese do conferences

Slide 13

Slide 13 text

RUBYKAIGI2009 See how the Japanese do conferences The translation time allows you to think more

Slide 14

Slide 14 text

RUBYKAIGI2009 See how the Japanese do conferences The translation time allows you to think more Meet nice Rubyists from Japan and other places

Slide 15

Slide 15 text

RUBYKAIGI2009 See how the Japanese do conferences The translation time allows you to think more Meet nice Rubyists from Japan and other places See Japan!

Slide 16

Slide 16 text

No content

Slide 17

Slide 17 text

No content

Slide 18

Slide 18 text

No content

Slide 19

Slide 19 text

No content

Slide 20

Slide 20 text

No content

Slide 21

Slide 21 text

No content

Slide 22

Slide 22 text

No content

Slide 23

Slide 23 text

No content

Slide 24

Slide 24 text

No content

Slide 25

Slide 25 text

No content

Slide 26

Slide 26 text

No content

Slide 27

Slide 27 text

No content

Slide 28

Slide 28 text

MIXIN MODULES

Slide 29

Slide 29 text

A TRIVIAL MIXIN I’m sure most of us know this

Slide 30

Slide 30 text

A TRIVIAL MIXIN I’m sure most of us know this module Mixin def shared_method puts "Called!" end end ! class Whatever include Mixin end ! Whatever.new.shared_method

Slide 31

Slide 31 text

A TRIVIAL MIXIN I’m sure most of us know this module Mixin def shared_method puts "Called!" end end ! class Whatever include Mixin end ! Whatever.new.shared_method Called!

Slide 32

Slide 32 text

No content

Slide 33

Slide 33 text

No content

Slide 34

Slide 34 text

No content

Slide 35

Slide 35 text

No content

Slide 36

Slide 36 text

No content

Slide 37

Slide 37 text

class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! class E < A include B include C include D def call puts "E" super end end ! E.new.call

Slide 38

Slide 38 text

E D C B A class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! class E < A include B include C include D def call puts "E" super end end ! E.new.call

Slide 39

Slide 39 text

INHERITANCE p E.ancestors

Slide 40

Slide 40 text

INHERITANCE p E.ancestors [E, D, C, B, A, Object, Kernel, BasicObject]

Slide 41

Slide 41 text

No content

Slide 42

Slide 42 text

No content

Slide 43

Slide 43 text

No content

Slide 44

Slide 44 text

No content

Slide 45

Slide 45 text

No content

Slide 46

Slide 46 text

class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! a = A.new a.extend(B) a.extend(C) a.extend(D) a.call

Slide 47

Slide 47 text

class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! a = A.new a.extend(B) a.extend(C) a.extend(D) a.call D C B A

Slide 48

Slide 48 text

INVISIBLE CLASS class << a; p ancestors end

Slide 49

Slide 49 text

INVISIBLE CLASS class << a; p ancestors end [D, C, B, A, Object, Kernel, BasicObject]

Slide 50

Slide 50 text

INVISIBLE CLASS class << a; p ancestors end [D, C, B, A, Object, Kernel, BasicObject] The (invisible) “singleton class” is here

Slide 51

Slide 51 text

No content

Slide 52

Slide 52 text

class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! a = A.new a.extend(B) a.extend(C) a.extend(D) class << a def call puts "Invisible" super end end a.call

Slide 53

Slide 53 text

class A def call puts "A" end end ! %w[B C D].each do |name| eval <<-END_RUBY module #{name} def call puts "#{name}" super end end END_RUBY end ! a = A.new a.extend(B) a.extend(C) a.extend(D) class << a def call puts "Invisible" super end end a.call Invisible D C B A

Slide 54

Slide 54 text

JUST A SHORTCUT We now know what extend() really is

Slide 55

Slide 55 text

JUST A SHORTCUT We now know what extend() really is obj.extend(Mod)

Slide 56

Slide 56 text

JUST A SHORTCUT We now know what extend() really is obj.extend(Mod) class << obj include Mod end

Slide 57

Slide 57 text

NAMESPACE MODULES

Slide 58

Slide 58 text

GROUP CONSTANTS Group constants/classes and even mix them in

Slide 59

Slide 59 text

GROUP CONSTANTS Group constants/classes and even mix them in class Logger # ... # Logging severity. module Severity DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 FATAL = 4 UNKNOWN = 5 end include Severity # ... end

Slide 60

Slide 60 text

GROUP CONSTANTS Group constants/classes and even mix them in class Logger # ... # Logging severity. module Severity DEBUG = 0 INFO = 1 WARN = 2 ERROR = 3 FATAL = 4 UNKNOWN = 5 end include Severity # ... end module JSON class Array # ... end class Object # ... end # ... end

Slide 61

Slide 61 text

No content

Slide 62

Slide 62 text

No content

Slide 63

Slide 63 text

No content

Slide 64

Slide 64 text

No content

Slide 65

Slide 65 text

DUAL INTERFACE Some modules are both a namespace and a mixin

Slide 66

Slide 66 text

DUAL INTERFACE Some modules are both a namespace and a mixin module MoreMath def self.dist(x1, y1, x2, y2) Math.sqrt( (x2 - x1) ** 2 + (y2 - y1) ** 2 ) end end

Slide 67

Slide 67 text

DUAL INTERFACE Some modules are both a namespace and a mixin module MoreMath def self.dist(x1, y1, x2, y2) Math.sqrt( (x2 - x1) ** 2 + (y2 - y1) ** 2 ) end end module MoreMath extend Math def self.dist( x1, y1, x2, y2 ) sqrt( (x2 - x1) ** 2 + (y2 - y1) ** 2 ) end end

Slide 68

Slide 68 text

MIXIN YOURSELF Better than Ruby’s module_function()

Slide 69

Slide 69 text

MIXIN YOURSELF Better than Ruby’s module_function() module MiniLogger extend self def logger $stdout end def log(message) logger.puts "%s: %s" % [ Time.now.strftime("%D %H:%M:%S"), message ] end end ! if __FILE__ == $PROGRAM_NAME MiniLogger.log "Called as a module method and " + "written to $stdout." end

Slide 70

Slide 70 text

MIXIN YOURSELF Better than Ruby’s module_function() require "mini_logger" ! class Whatever include MiniLogger def logger @logger ||= open("whatever.log", "w") end def initialize log "Called as an " + "instance method " + "and written to " + "a file." end end ! Whatever.new module MiniLogger extend self def logger $stdout end def log(message) logger.puts "%s: %s" % [ Time.now.strftime("%D %H:%M:%S"), message ] end end ! if __FILE__ == $PROGRAM_NAME MiniLogger.log "Called as a module method and " + "written to $stdout." end

Slide 71

Slide 71 text

No content

Slide 72

Slide 72 text

No content

Slide 73

Slide 73 text

No content

Slide 74

Slide 74 text

No content

Slide 75

Slide 75 text

LIMITED MAGIC Summon new error types as needed

Slide 76

Slide 76 text

LIMITED MAGIC Summon new error types as needed module Errors class BaseError < RuntimeError; end def self.const_missing(error_name) if error_name.to_s =~ /\wError\z/ const_set(error_name, Class.new(BaseError)) else super end end end ! p Errors::SaveError

Slide 77

Slide 77 text

SOME EXAMPLES Bridging the theory to implementation gap

Slide 78

Slide 78 text

SOME EXAMPLES Bridging the theory to implementation gap

Slide 79

Slide 79 text

A BIT TOO CLEVER If RDoc can’t read it, it’s probably too clever

Slide 80

Slide 80 text

A BIT TOO CLEVER If RDoc can’t read it, it’s probably too clever require "ostruct" ! class << Config = OpenStruct.new def update_from_config_file(path = config_file) eval <<-END_UPDATE config = self #{File.read(path)} config END_UPDATE end # ... end ! Config.config_file = "config.rb" Config.update_from_config_file

Slide 81

Slide 81 text

A BIT TOO CLEVER If RDoc can’t read it, it’s probably too clever require "ostruct" ! class << Config = OpenStruct.new def update_from_config_file(path = config_file) eval <<-END_UPDATE config = self #{File.read(path)} config END_UPDATE end # ... end ! Config.config_file = "config.rb" Config.update_from_config_file config.command = "ls" config.retries = 42 # ...

Slide 82

Slide 82 text

LESS MAGIC RDoc and I can both read it now

Slide 83

Slide 83 text

LESS MAGIC RDoc and I can both read it now require "ostruct" ! # These extra methods are mixed into the OpenStruct stored in Config. module Configured # This method loads configuration settings from a plain Ruby file. def update_from_config_file(path = config_file) eval <<-END_UPDATE config = self #{File.read(path)} config END_UPDATE end # ... end # This constant holds all global configuration, see Configured for details. Config = OpenStruct.new.extend(Configured)

Slide 84

Slide 84 text

No content

Slide 85

Slide 85 text

No content

Slide 86

Slide 86 text

No content

Slide 87

Slide 87 text

No content

Slide 88

Slide 88 text

WITH CLASS METHODS A classic pattern made popular by Rails

Slide 89

Slide 89 text

WITH CLASS METHODS A classic pattern made popular by Rails module DoubleMixin module ClassMethods # ... end module InstanceMethods # ... end def self.included(receiver) receiver.extend(ClassMethods) receiver.send(:include, InstanceMethods) end end

Slide 90

Slide 90 text

No content

Slide 91

Slide 91 text

No content

Slide 92

Slide 92 text

No content

Slide 93

Slide 93 text

No content

Slide 94

Slide 94 text

LABELING OBJECTS You can use a do-nothing module as a type

Slide 95

Slide 95 text

LABELING OBJECTS You can use a do-nothing module as a type module DRb # ... module DRbUndumped def _dump(dummy) # :nodoc: raise TypeError, 'can\'t dump' end end # ... class DRbMessage # ... def dump(obj, error=false) # :nodoc: obj = make_proxy(obj, error) if obj.kind_of? DRbUndumped # ... end # ... end # ... end

Slide 96

Slide 96 text

OBJECT EDITING Using hooks to edit objects

Slide 97

Slide 97 text

OBJECT EDITING Using hooks to edit objects p "ruby".strip!. capitalize! ! # NoMethodError: # undefined method # `capitalize!' for # nil:NilClass

Slide 98

Slide 98 text

OBJECT EDITING Using hooks to edit objects module SafelyChainable def self.extended(singleton) singleton.methods.grep(/\w!\z/). each do |bang| singleton.instance_eval <<-END_RUBY def #{bang} super self end END_RUBY end end end ! p "ruby".extend(SafelyChainable). strip!.capitalize! p "ruby".strip!. capitalize! ! # NoMethodError: # undefined method # `capitalize!' for # nil:NilClass

Slide 99

Slide 99 text

SUMMARY

Slide 100

Slide 100 text

SUMMARY

Slide 101

Slide 101 text

SUMMARY Master Ruby’s method lookup; it’s worth the effort

Slide 102

Slide 102 text

SUMMARY Master Ruby’s method lookup; it’s worth the effort Modules are a terrific at limiting the scope of magic

Slide 103

Slide 103 text

SUMMARY Master Ruby’s method lookup; it’s worth the effort Modules are a terrific at limiting the scope of magic Remember, modules can modify individual objects

Slide 104

Slide 104 text

SUMMARY Master Ruby’s method lookup; it’s worth the effort Modules are a terrific at limiting the scope of magic Remember, modules can modify individual objects Try replacing some inheritance with extend()

Slide 105

Slide 105 text

QUESTIONS?