Class: Module

Inherits:
Object
  • Object
show all
Defined in:
lib/chainy/module.rb

Instance Method Summary collapse

Instance Method Details

#chain_attr_accessor(symbol, *args) ⇒ Object



2
3
4
5
6
7
8
9
10
11
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/chainy/module.rb', line 2

def chain_attr_accessor(symbol, *args)
  if args.last.is_a?(Hash)
    opts = args.pop
  else
    opts = {}
  end

  attr_accessor(symbol, *args)

  prefix = opts[:prefix] || Chainy::Config.prefix

  [].tap do |method_names|
    method_names << symbol
    method_names.concat args
  end.each do |getter_method|
    instance_variable_name = "@#{getter_method}"

    if opts[:hash]
      define_method(getter_method) do
        instance_variable_set instance_variable_name, instance_variable_get(instance_variable_name) || {}
      end
    end

    new_method_name = "#{prefix}_#{getter_method}"

    if opts[:hash]

      define_method(new_method_name) do |hash|
        instance_variable_set instance_variable_name, send(getter_method).merge(hash)
        self
      end

      define_method("without_#{getter_method}") do |*keys|
        keys.each do |key|
          send(getter_method).delete(key)
        end
        self
      end

    else

      define_method(new_method_name) do |*args|
        send "#{getter_method}=", *args
        self
      end

    end
  end
end