Class: Usable::ModExtender

Inherits:
Object
  • Object
show all
Defined in:
lib/usable/mod_extender.rb

Constant Summary collapse

SPEC =
:UsableSpec
CLASS_MODULE =
:ClassMethods

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mod, options = {}) ⇒ ModExtender

Returns a new instance of ModExtender.



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/usable/mod_extender.rb', line 9

def initialize(mod, options = {})
  @mod = mod
  @options = options
  @options[:method] ||= :include
  if has_spec?
    @copy = mod.const_get SPEC
    @name = "#{mod.name}UsableSpec"
  else
    @copy = mod
    @name = mod.name
  end
  @unwanted = options[:only] ? @copy.instance_methods - Array(options[:only]) : []
  if @unwanted.any?
    @copy = @copy.dup
  end
end

Instance Attribute Details

#copyObject

Returns the value of attribute copy.



7
8
9
# File 'lib/usable/mod_extender.rb', line 7

def copy
  @copy
end

#modObject

Returns the value of attribute mod.



7
8
9
# File 'lib/usable/mod_extender.rb', line 7

def mod
  @mod
end

#nameObject (readonly)

Returns the value of attribute name.



6
7
8
# File 'lib/usable/mod_extender.rb', line 6

def name
  @name
end

#optionsObject

Returns the value of attribute options.



7
8
9
# File 'lib/usable/mod_extender.rb', line 7

def options
  @options
end

#unwantedObject

Returns the value of attribute unwanted.



7
8
9
# File 'lib/usable/mod_extender.rb', line 7

def unwanted
  @unwanted
end

Instance Method Details

#has_spec?Boolean

Returns:

  • (Boolean)


59
60
61
# File 'lib/usable/mod_extender.rb', line 59

def has_spec?
  mod.const_defined? SPEC
end

#mod_nameObject



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

def mod_name
  if name
    name.split('::').last
  else
    "UsableMod#{Time.now.strftime('%s')}"
  end
end

#overrideObject

Note:

Destructive, as it changes @copy



27
28
29
30
31
# File 'lib/usable/mod_extender.rb', line 27

def override
  unwanted.each do |method_name|
    copy.send :remove_method, method_name
  end
end

#use!(target) ⇒ Object



35
36
37
38
39
40
41
42
43
44
# File 'lib/usable/mod_extender.rb', line 35

def use!(target)
  override
  if copy.name.nil?
    const_name = "#{mod_name}Used"
    target.send :remove_const, const_name if target.const_defined? const_name, false
    target.const_set const_name, copy
  end
  target.usables.add_module copy
  target.send options[:method], copy
end

#use_class_methods!(target) ⇒ Object



54
55
56
57
# File 'lib/usable/mod_extender.rb', line 54

def use_class_methods!(target)
  return unless mod.const_defined? CLASS_MODULE
  target.extend mod.const_get CLASS_MODULE
end

#use_original!(target) ⇒ Object



47
48
49
50
51
# File 'lib/usable/mod_extender.rb', line 47

def use_original!(target)
  return unless has_spec?
  target.usables.add_module mod
  target.send options[:method], mod
end