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[: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.



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)
  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

#mod_nameObject



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

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

#overrideObject

Note:

Destructive, as it changes @copy



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

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

#use_class_methods!(target) ⇒ Object



39
40
41
42
# File 'lib/usable/mod_extender.rb', line 39

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

#use_instance_methods!(target) ⇒ Object



45
46
47
48
# File 'lib/usable/mod_extender.rb', line 45

def use_instance_methods!(target)
  return unless mod.const_defined? :InstanceMethods
  target.include mod.const_get :InstanceMethods
end