Ruby is a single inheritance language, similar to Swift in iOS, which is also single inheritance. In Swift, we can use the combination of Protocol and extension to achieve the effect of multiple inheritance. In Ruby, multiple inheritance can be achieved using a combination of modules and includes.
Mix-in
Class Person // 1 end module PlayPianoMixin // 2 def playPiano puts "..." End end class XiaoMing < Person include PlayPianoMixin //3 end p1 = XiaoMing. New () p1.playpiano () // 4Copy the code
- 1. Define a
Person
Class. - 2. Define one
PlayPianoMixin
themodule
. - 3. In concrete classes
inclue
specificmodule
.
In this way, we abstract the PlayPian into a Modlue. When the corresponding class needs to be described, we can use mix-in mode to inclue the PlayPian to obtain the corresponding capabilities.
Mix-in expectations are a collection of behaviors that can be added to any class. To some extent, inheritance describes “what it is”, while mix-in describes “what it can do”. From this point of view, mix-in design is a single responsibility. And mix-in actually knows nothing about the host class
Mix-in in Cocoapods
In The Config.rb for CocoaPods, there are many Pods configuration fields, some key directories for CocoaPods, and some singleton managers.
// config.rb
# Provides support for accessing the configuration instance in other
# scopes.
#
module Mixin
def config
Config.instance
end
end
Copy the code
A singleton is defined in mix-in mode. In other files, use include to obtain configuration information
// installer.rb
class Installer
include Config::Mixin
....
def integrate_user_project
...
installation_root = config.installation_root
end
end
Copy the code
After inclue, you can use the Config object directly.
This article extracts from a melon technology CocoaPods in Ruby features mix-in, the author recently is learning Ruby and learning CocoaPods implementation principle, read the knowledge point, in writing, MY heart will feel practical, so I excerpted this article.