Ruby fakeredis 源码的一个 module 设计

chenge · 2014年06月17日 · 最后由 chenge 回复于 2014年06月17日 · 1893 次阅读

为何 Connection 设计为 class 内的 module,这样有何作用呢?


class Redis
  module Connection
    class Memory
      include Redis::Connection::CommandHelper
      include FakeRedis
      include SortMethod
      include TransactionCommands
      include CommandExecutor

      attr_accessor :options

      # Tracks all databases for all instances across the current process.
      # We have to be able to handle two clients with the same host/port accessing
      # different databases at once without overwriting each other. So we store our
      # "data" outside the client instances, in this class level instance method.
      # Client instances access it with a key made up of their host/port, and then select
      # which DB out of the array of them they want. Allows the access we need.
      def self.databases
        @databases ||= Hash.new {|h,k| h[k] = [] }
      end

      # Used for resetting everything in specs
      def self.reset_all_databases
        @databases = nil
      end

      def self.connect(options = {})
        new(options)
      end

      def initialize(options = {})
        self.options = options
      end

可以按照 namespace 来理解。

#1 楼 @lgn21st 应该是这个意思。

def self.connect(options = {})
  new(options)
end

这个也比较有特色。

Hash.new {|h,k| h[k] = [] }

后面那个块参数起什么作用?

发现 ruby 全是 module 和 class。。。

@chenge Hash.new {|h,k| h[k] = [] }返回的值虽然也是{}, 但这个设计可以保证每一个不存在的 key 都会返回一个空 array, 而不是 nil

h = Hash.new {|h,k| h[k] = [] }
#=> {}

a = {}
#= {}

h == a
#=> true

# 下面差别出来了
h["foo"]
#=> []

a["foo"]
#=> nil

#4 楼 @billy 明白了,是个缺省。文档有说明。谢谢!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号