Class: Usable::ModExtender

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

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

Returns a new instance of ModExtender.



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

def initialize(mod, options = {})
  @mod = mod
  @options = options
  @options[:method] ||= :include
  @copy = mod
  @name = mod.name
  @unwanted = (options[:except] && Array(options[:except])) || find_unwanted_methods(options[:only])
  if @unwanted.any?
    @copy = @copy.dup
  end
end

Instance Attribute Details

#copyObject

Returns the value of attribute copy.



4
5
6
# File 'lib/usable/mod_extender.rb', line 4

def copy
  @copy
end

#modObject

Returns the value of attribute mod.



4
5
6
# File 'lib/usable/mod_extender.rb', line 4

def mod
  @mod
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/usable/mod_extender.rb', line 3

def name
  @name
end

#optionsObject

Returns the value of attribute options.



4
5
6
# File 'lib/usable/mod_extender.rb', line 4

def options
  @options
end

#unwantedObject

Returns the value of attribute unwanted.



4
5
6
# File 'lib/usable/mod_extender.rb', line 4

def unwanted
  @unwanted
end

Instance Method Details

#call(target) ⇒ Object



20
21
22
23
24
25
26
27
28
29
# File 'lib/usable/mod_extender.rb', line 20

def call(target)
  unwanted.each(&method(:remove_from_module))
  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 if target.respond_to?(:usables)
  target.send options[:method], copy
end

#find_unwanted_methods(only) ⇒ Object



39
40
41
42
43
44
45
46
# File 'lib/usable/mod_extender.rb', line 39

def find_unwanted_methods(only)
  return [] unless only
  if :constants == only
    @copy.instance_methods
  else
    @copy.instance_methods - Array(only)
  end
end

#mod_nameObject



31
32
33
34
35
36
37
# File 'lib/usable/mod_extender.rb', line 31

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

#remove_from_module(method_name) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/usable/mod_extender.rb', line 48

def remove_from_module(method_name)
  begin
    copy.send :remove_method, method_name
  rescue NameError => e
    # Expected sometimes, like it could be raised trying to remove a superclass method
    Usable.logger.debug("#{e.class}: #{e.message}")
  end
  # Block access to superclass method, and prevent it from being copied to the target
  copy.send :undef_method, method_name if copy.instance_methods.include?(method_name)
end