Class: Class

Inherits:
Object show all
Defined in:
lib/lib/base.rb

Instance Method Summary collapse

Instance Method Details

#cattr(name = nil, opts = {}, &block) ⇒ 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
51
52
53
54
55
# File 'lib/lib/base.rb', line 2

def cattr name = nil, opts = {}, &block
  if name
    # cattr :foo, class: true, instance: true, default: proc { bar }

    unless opts.class == Hash
      raise ArgumentError, 'Options are not a Hash'
    end

    # if block provided, set it as a default value
    if block
      opts[:default] = block
    end

    # set class methods
    if opts[:class]
      define_singleton_method('%s=' % name) do |arg|
        CattrProxy.new(self).send('%s=' % name, arg)
      end

      define_singleton_method(name) do |arg = :_nil|
        if arg == :_nil
          CattrProxy.new(self).send(name)
        else
          CattrProxy.new(self).send('%s=' % name, arg)
        end
      end
    end

    # set instance methods
    if opts[:instance]
      define_method('%s=' % name) do |arg|
        CattrProxy.new(self.class).send('%s=' % name, arg)
      end

      define_method(name) do
        CattrProxy.new(self.class).send(name)
      end
    end

    # capture bad arguments
    supported = [:default, :class, :instance]
    invalid = opts.keys - supported
    if invalid.first
      raise ArgumentError, 'Invalid argument :%s, supported: %s' % [invalid.first, supported.join(', ')]
    end

    # set values
    CattrProxy.new(self).send('%s=' % name, opts[:default])
  else
    # Klass.cattr.foo

    CattrProxy.new(self)
  end
end