-
Notifications
You must be signed in to change notification settings - Fork 0
/
L3-more-classes-modules.rb
82 lines (62 loc) · 1.13 KB
/
L3-more-classes-modules.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
# Requirements change! We want to our play list to include movies
class Media
attr_accessor :name, :artist
def initialize(name, artist)
@name = name
@artist = artist
end
def to_s
name
end
end
class Track < Media
def to_s
"[TRACK] #{super}"
end
end
class Movie < Media
def to_s
"[MOVIE] #{super}"
end
end
track = Track.new("Somebody", "Gotye")
puts track
movie = Movie.new("Officespace", "Mike Judge")
puts movie
# Mixins - Ruby's answer to multiple inheritance
module AudioPlayer
def play
puts "Now playing - #{name}"
end
end
# Let's do it live!
class Track
include AudioPlayer
end
track.play
# how do we protect against a missing name method?
module MoviePlayer
def play
if self.respond_to?(:name)
puts "****** Now Playing #{name}"
else
puts "I don't know how to play that!"
end
end
end
class NotAMovie
include MoviePlayer
end
obj = NotAMovie.new
obj.play
#What about a movie?
class Movie
include MoviePlayer
end
movie.play
# Modules aren't just for mixins, you can use them for namespacing
module CheapTunes
class Track
end
end
CheapTunes::Track.new