Module: CIMAttributes::ClassMethods

Defined in:
lib/cim_attributes.rb

Instance Method Summary collapse

Instance Method Details

#cim_attr_accessor(*args) ⇒ Object

Raises:

  • (ArgumentError)


71
72
73
74
75
# File 'lib/cim_attributes.rb', line 71

def cim_attr_accessor(*args)
  raise ArgumentError, 'no args for cim_attr_accessor' unless args.size > 0
  cim_attr_reader(*args)
  cim_attr_writer(*args)
end

#cim_attr_reader(*args) ⇒ Object

Raises:

  • (ArgumentError)


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
56
57
58
59
60
# File 'lib/cim_attributes.rb', line 7

def cim_attr_reader(*args)
  raise ArgumentError, 'no args for cim_attr_reader' unless args.size > 0
  opts = if args.last.is_a?(Hash)
           args.pop
         else
           {}
         end
  args.each do |attr|

    ## class methods

    target, message = *(if self.respond_to? :define_singleton_method
                          [self, :define_singleton_method]
                        else
                          [class << self; self; end, :define_method]
                        end)

    target.send message, attr do 
      self.instance_variable_get("@#{attr}") || if self.superclass.respond_to?(attr)
                                                  self.superclass.send(attr)
                                                else
                                                  nil
                                                end
    end

    target.send message, "#{attr}=" do |val|
      self.instance_variable_set("@#{attr}", val)
    end

    target.send message, "with_#{attr}" do |val, &blk|
      if val || (val = self.send(attr))
        blk.call(val)
      else
        raise("no #{attr} defined for #{self} and none passed in")
      end
    end

    ## instance methods

    self.send :define_method, attr do
      self.instance_variable_get("@#{attr}") || self.class.send(attr)
    end

    self.send :define_method, "#{attr}=" do |val|
      self.instance_variable_set("@#{attr}", val)
    end

    self.send :define_method, "ensure_#{attr}!" do
      if !self.send(attr)
        raise("no #{attr} defined for #{self}")
      end
    end
  end
end

#cim_attr_writer(*args) ⇒ Object

Raises:

  • (ArgumentError)


62
63
64
65
66
67
68
69
# File 'lib/cim_attributes.rb', line 62

def cim_attr_writer(*args)
  raise ArgumentError, 'no args for cim_attr_writer' unless args.size > 0
  opts = if args.last.is_a?(Hash)
           args.pop
         else
           {}
         end
end