-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy path5-modules_and_mixins.rb
61 lines (48 loc) · 1.16 KB
/
5-modules_and_mixins.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
# ================================
# Modules
#
# modlules are much like a classes but
# unlike classes it cannot be instantiated.
# modules are stand-alone libraries of code
# that are ideal for mixins and exteding
# existing objects.
# ================================
# =================
# module
# =================
module Foo
#...
end
# include/extend
class Bar
include Foo # if you want Foo as instance methods
extend Foo # if you want Foo as class methods
end
# ================================
# common mixin paradigm
# ================================
module PaymentSystem
# this is a ruby hook that gets
# called when a module is included
# in a class. The said class gets
# passed in as an argument.
def included(klass)
klass.extend(ClassMethods)
end
# instance methods
def pay
# pay person
end
# class methods
module ClassMethods
def probation
# finds people who are on probation
end
end
end
class Employee
include PaymentSystem
# we now have both the
# instance and class methods
# from PaymentSystem
end