Class: Module

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

Overview

Some core ruby extensions

Instance Method Summary collapse

Instance Method Details

#basenameObject

From the Facets package

returns the name of the class or module without the namespace prefix.



55
56
57
58
59
60
61
# File 'lib/ruby_ext.rb', line 55

def basename
  if name and not name.empty?
    name.gsub(/^.*::/, '')
  else
    nil #inspect.gsub('#<','').gsub('>','').sub(':', '_')
  end
end

#insert(new_mod) ⇒ Object

WARNING : This is a dangerous method

It’s like include but changes the order so that the new module is before the older one.



23
24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ruby_ext.rb', line 23

def insert(new_mod)
  new_mod = new_mod.dup
  old_mod = self
  mod_name = self.basename

  new_mod.module_eval do
    include old_mod
  end

  (nesting[-2] || Object).module_eval do
    remove_const mod_name
    const_set mod_name, new_mod
  end
end

#nestingObject

From the Facets package

Returns an array of all the parents in the namespace name.

ex. YourApp::Models::Page #=> [YourApp::Models::Page, YourApp::Models, YourApp]



44
45
46
47
48
# File 'lib/ruby_ext.rb', line 44

def nesting
  n = []
  name.split(/::/).inject(self){ |mod, name| c = mod.const_get(name) ; n << c ; c }
  return n
end

#transfer_classes_to(dest, force = false) ⇒ Object

Utility method to transfer all classes of a module into another. It is useful when you write Camping extensions. cf. other equipments.

I’m using this to override ServerError and NotFound controllers.



9
10
11
12
13
14
15
16
17
# File 'lib/ruby_ext.rb', line 9

def transfer_classes_to(dest, force=false)
  constants.each do |str|
    k = const_get(str)
    if k.kind_of? Class
      dest.send :remove_const, str if force and dest.const_defined? str
      dest.const_set str, k.dup unless dest.const_defined? str
    end
  end
end