Class: Strada::ConfigStruct

Inherits:
Object
  • Object
show all
Defined in:
lib/strada/config_struct.rb

Instance Method Summary collapse

Constructor Details

#initialize(hash = nil, opts = {}) ⇒ ConfigStruct

类对象初始化函数入口



6
7
8
9
# File 'lib/strada/config_struct.rb', line 6

def initialize(hash = nil, opts = {})
  @key_to_s = opts.delete(:key_to_s) || false
  @cfg      = hash ? _config_from_hash(hash) : {}
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(name, *args, &block) ⇒ Object

方法反射



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
# File 'lib/strada/config_struct.rb', line 12

def method_missing(name, *args, &block)
  name = name.to_s
  # 检索 ConfigStruct 键值对
  # strada.cfg['foo']
  name = args.shift if name[0..1] == "[]"
  arg  = args.first

  if name[-1..-1] == "?"
    # 查询是否包含某个 KEY
    # strada.cfg.foo.bar?
    if @cfg.has_key? name[0..-2]
      @cfg[name[0..-2]]
    else
      nil
    end
  elsif name[-1..-1] == "="
    # strada.cfg.foo.bar = 'bala'
    # ConfigStruct 键值对赋值
    _config_set name[0..-2], arg
  else
    # strada.cfg.foo.bar
    # ConfigStruct 查询某个属性
    _config_get name, arg
  end
end

Instance Method Details

#_config_to_hashObject

将配置信息转换为 HASH 对象



39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/strada/config_struct.rb', line 39

def _config_to_hash
  hash = {}
  @cfg.each do |key, value|
    if value.class == ConfigStruct
      value = value._config_to_hash
    end
    # 是否需要将 key 转为 to_s
    key = key.to_s if @key_to_s
    # 保存键值对数据到 HASH
    hash[key] = value
  end
  hash
end

#each(&block) ⇒ Object

调用配置 each 方法执行代码块



59
60
61
# File 'lib/strada/config_struct.rb', line 59

def each(&block)
  @cfg.each(&block)
end

#empty?Boolean

是否为空配置

Returns:

  • (Boolean)


54
55
56
# File 'lib/strada/config_struct.rb', line 54

def empty?
  @cfg.empty?
end

#has_key?(key) ⇒ Boolean

判断配置是否包含某个属性

Returns:

  • (Boolean)


69
70
71
# File 'lib/strada/config_struct.rb', line 69

def has_key?(key)
  @cfg.has_key? key
end

#keysObject

配置的相关属性



64
65
66
# File 'lib/strada/config_struct.rb', line 64

def keys
  @cfg.keys
end