Module: Maintain::Backend

Defined in:
lib/maintain/backend.rb,
lib/maintain/backend/base.rb,
lib/maintain/backend/data_mapper.rb,
lib/maintain/backend/active_record.rb

Defined Under Namespace

Classes: ActiveRecord, Base, DataMapper

Class Method Summary collapse

Class Method Details

.add(name, owner) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
# File 'lib/maintain/backend.rb', line 6

def add(name, owner)
  classes[name.to_sym] = owner
  # Dig through the constant name to find if it exists
  modules = owner.split('::')
  if Object.const_defined?(modules.first) && owner = Object.const_get(modules.shift)
    while modules.length > 0
      owner = owner.const_get(modules.shift)
    end
    # If it exists, extend it with Maintain methods automatically
    owner.extend Maintain
  end
end

.build(back_end) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
# File 'lib/maintain/backend.rb', line 19

def build(back_end)
  back_end = back_end.to_s.split('_').map(&:capitalize).join('')
  if constants.include? back_end.to_s
    const_get(back_end.to_sym).new
  else
    begin
      back_end = const_missing(back_end)
      back_end.new
    rescue
    end
  end
end

.classesObject



32
33
34
# File 'lib/maintain/backend.rb', line 32

def classes
  @classes ||= {}
end

.const_missing(constant) ⇒ Object



36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/maintain/backend.rb', line 36

def const_missing(constant)
  underscore_constant = constant.to_s.dup
  underscore_constant.gsub!(/::/, '/')
  underscore_constant.gsub!(/([A-Z]+)([A-Z][a-z])/,'\1_\2')
  underscore_constant.gsub!(/([a-z\d])([A-Z])/,'\1_\2')
  underscore_constant.tr!("-", "_")
  underscore_constant.downcase!
  begin
    require("maintain/backend/#{underscore_constant}")
    const_get(constant)
  rescue
    super
  end
end

.detect(owner) ⇒ Object

Detect if we’ve loaded a backend for this class - that means if its ancestors or parent classes include any of our back-end classes.



53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/maintain/backend.rb', line 53

def detect(owner)
  ancestors = owner.ancestors.map(&:to_s)
  # While owner does not refer to "Object"
  while owner.superclass
    ancestors.push(owner.to_s)
    owner = owner.superclass
  end
  classes.each do |back_end, class_name|
    if ancestors.include? class_name
      return back_end
    end
  end
  nil
end