Class: Configurable::NestConfig

Inherits:
Config show all
Defined in:
lib/configurable/nest_config.rb

Overview

NestConfigs are used to nest configurable classes.

Instance Attribute Summary collapse

Attributes inherited from Config

#attributes, #reader, #writer

Instance Method Summary collapse

Methods inherited from Config

#[], duplicable_value?, #init?

Constructor Details

#initialize(nest_class, reader, writer = "#{reader}=", attributes = {}, init = true) ⇒ NestConfig

Initializes a new NestConfig



12
13
14
15
16
17
18
# File 'lib/configurable/nest_config.rb', line 12

def initialize(nest_class, reader, writer="#{reader}=", attributes={}, init=true)
  self.nest_class = nest_class
  self.reader = reader
  self.writer = writer
  @attributes = attributes
  @init = init
end

Instance Attribute Details

#nest_classObject

The nested configurable class



9
10
11
# File 'lib/configurable/nest_config.rb', line 9

def nest_class
  @nest_class
end

Instance Method Details

#defaultObject

Returns a hash of the default configuration values for nest_class.



21
22
23
24
25
26
27
# File 'lib/configurable/nest_config.rb', line 21

def default
  default = {}
  nest_class.configurations.each_pair do |key, delegate|
    default[key] = delegate.default
  end
  default
end

#get(receiver) ⇒ Object

Calls the reader on the reciever to retreive an instance of the nest_class and returns it’s config. Returns nil if the reader returns nil.



32
33
34
35
36
37
38
# File 'lib/configurable/nest_config.rb', line 32

def get(receiver)
  if instance = receiver.send(reader)
    instance.config
  else
    nil
  end
end

#init(receiver) ⇒ Object

Initializes an instance of nest_class and sets it on the receiver. The instance is initialized by calling nest_class.new with no arguments.



57
58
59
# File 'lib/configurable/nest_config.rb', line 57

def init(receiver)
  receiver.send(writer, nest_class.new)
end

#inspectObject

Returns an inspection string.



62
63
64
# File 'lib/configurable/nest_config.rb', line 62

def inspect
  "#<#{self.class}:#{object_id} reader=#{reader} writer=#{writer} nest_class=#{nest_class.inspect} >"
end

#set(receiver, value) ⇒ Object

Calls the reader on the reciever to retrieve an instance of the nest_class, and reconfigures it with value. The instance will be initialized by init if necessary.

If value is an instance of the nest_class, then it will be set by calling writer.



46
47
48
49
50
51
52
53
# File 'lib/configurable/nest_config.rb', line 46

def set(receiver, value)
  if value.kind_of?(nest_class)
    receiver.send(writer, value)
  else
    configurable = receiver.send(reader) || init(receiver)
    configurable.reconfigure(value)
  end
end