Module: Cube::Trait

Defined in:
lib/cube/traits.rb

Defined Under Namespace

Classes: IncludeError, MethodConflict

Instance Method Summary collapse

Instance Method Details

#append_features(mod) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# File 'lib/cube/traits.rb', line 16

def append_features(mod)
  if mod.is_a?(Class) && !mod.is_a?(CubeMethods)
    raise IncludeError, "Traits can only be mixed into cube classes"
  end
  unless mod.instance_variable_defined?(:@__trait_allow_include) &&
    mod.instance_variable_get(:@__trait_allow_include)
    raise IncludeError, "Traits can only be mixed in using method `with_trait`"
  end
  conflicts = public_instance_methods & mod.public_instance_methods
  errors = conflicts.map { |c|
    meth = mod.instance_method(c)
    if meth.owner.is_a?(Class)
      if meth.owner == mod.superclass
        module_exec { remove_method(c) }
      end
      nil
    else
      { meth: meth, owner: meth.owner }
    end
  }.compact
  unless errors.empty?
    message = "\n" + errors.map { |e| e[:meth].to_s }.join("\n")
    raise MethodConflict, message
  end
  if @__interface_trait_required_interface && mod.is_a?(Class)
    intf = @__interface_trait_required_interface
    mod.include?(intf) || mod.as_interface(intf, runtime_checks: false)
  end
  super
end

#requires_interface(intf) ⇒ Object



9
10
11
12
13
14
# File 'lib/cube/traits.rb', line 9

def requires_interface(intf)
  unless intf.is_a? Cube::Interface
    raise ArgumentError, "#{intf} is not a Cube::Interface"
  end
  @__interface_trait_required_interface = intf
end