Class: Module

Inherits:
Object show all
Defined in:
lib/r_kit/utility/module_extend.rb

Instance Method Summary collapse

Instance Method Details

#attr_reader(*names, default: nil) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/r_kit/utility/module_extend.rb', line 13

def attr_reader *names, default: nil
  if default
    names.each do |name|
      define_method name do
        instance_variable_get("@#{ name }") ||
          instance_variable_set("@#{ name }", default.is_a?(Proc) ? default.call(self, name) : default)
      end
    end
  else
    basic_attr_reader *names
  end
end

#basic_attr_readerObject



12
# File 'lib/r_kit/utility/module_extend.rb', line 12

alias :basic_attr_reader :attr_reader

#basic_const_getObject



50
# File 'lib/r_kit/utility/module_extend.rb', line 50

alias :basic_const_get :const_get

#const_get(name, *args, default: nil) ⇒ Object



51
52
53
54
55
56
57
58
# File 'lib/r_kit/utility/module_extend.rb', line 51

def const_get name, *args, default: nil
  if default && !const_defined?(name)
    name.safe_constantize ||
      const_set(name, default)
  else
    basic_const_get name, *args
  end
end

#const_replace(name, value) ⇒ Object



60
61
62
63
# File 'lib/r_kit/utility/module_extend.rb', line 60

def const_replace name, value
  remove_const name
  const_set name, value
end

#namespaceObject



6
7
8
# File 'lib/r_kit/utility/module_extend.rb', line 6

def namespace
  (deconstantize.presence || 'Object').constantize
end

#singleton_attr_reader(*args, **options) ⇒ Object



45
46
47
# File 'lib/r_kit/utility/module_extend.rb', line 45

def singleton_attr_reader *args, **options
  singleton_class.send :attr_reader, *args, **options
end

#tap_attr_accessor(*names) ⇒ Object

TODO: these writter are called like “.name(value)” to set and return self or like “.name” to read TODO: to be used in ‘pagination’, these need an “after” callback (to set @limited_collection to nil) TODO: and to be used in ‘grid (base.rb, binding_accessor)’, these need an “to” delegation object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/r_kit/utility/module_extend.rb', line 31

def tap_attr_accessor *names
  names.each do |name|
    define_method name, ->(value = nil) do
      if value
        instance_variable_set "@#{ name }", value
        self
      else
        instance_variable_get "@#{ name }"
      end
    end
  end
end