目錄 (module 篇)
modules as being very much like classes, only modules can’t create instances and can’t have subclasses. They’re just used to store things!
- NAMESPACE
- MIXIN
1. NAMESPACE(避免同樣的 method name)
image_utils.rb
1 2 3 4 5 6 7
| module ImageUtils def self.preview(image) end def self.transfer(image, destination) end end
|
run.rb
1 2 3
| require 'image_utils' image = user.image ImageUtils.preview(image)
|
1 2 3 4 5
| module Math PI = 3.141592653589793 end puts Math::PI
|
2. MIXIN
include
: 可直接當作 instance method
來 include
IMAGE_UTILS.RB
1 2 3 4 5 6
| module ImageUtils def preview end def transfer(destination) end end
|
AVATAR.RB
1 2 3 4
| require 'image_utils' class Image include ImageUtils end
|
RUN.RB
1 2
| image = user.image image.preview
|
MIXINS(像是多重繼承) VS CLASS INHERITANCE(只能單一superclass)
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| class Post include Shareable include Favoritable end class Image include Shareable include Favoritable end class Tweet include Shareable include Favoritable end
|
1 2 3 4 5 6 7 8 9
| module Shareable def share_on_facebook end end  module Favoritable def add_to_delicious end end
|
extend
: 可直接當作 class method
來 extend
HOOKS
1 2 3 4 5 6 7 8 9 10 11 12 13
| module ImageUtils def preview end def transfer(destination) end module ClassMethods def fetch_from_twitter(user) end end end
|
1 2 3 4
| class Image include ImageUtils extend ImageUtils::ClassMethods end
|
1 2 3
| image = user.image image.preview # instance method Image.fetch_from_twitter('gregg') # class method
|