Module: LibXML::Ext::Uniq

Extended by:
Forwardable
Defined in:
lib/libxml/ext/uniq_mixin.rb

Constant Summary collapse

DELEGATORS =
%w[to_a each length size]

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



72
73
74
75
76
77
78
79
# File 'lib/libxml/ext/uniq_mixin.rb', line 72

def self.included(base)
  base.send(:alias_method, :_libxml_ext_original_to_a, :to_a)

  # overwrite original methods
  instance_methods.each { |method|
    base.send(:define_method, method, instance_method(method))
  }
end

Instance Method Details

#to_aObject



38
39
40
41
42
43
44
# File 'lib/libxml/ext/uniq_mixin.rb', line 38

def to_a
  ary  = _libxml_ext_original_to_a
  seen = Hash.new { |h, k| h[k] = true; false }

  # return unique nodes according to their #to_s
  @_uniq ? ary.delete_if { |node| seen[node.to_s] } : ary
end

#uniqObject



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/libxml/ext/uniq_mixin.rb', line 46

def uniq
  proxy = self.class.new.uniq!
  proxy.instance_variable_set(:@_this, self)

  class << proxy
    (instance_methods.map { |m| m.to_s } - DELEGATORS).each { |method|
      undef_method(method) unless method =~ /\A__/ || method == 'object_id'
    }

    def method_missing(*args)
      @_this.send(*args, &block_given? ? Proc.new : nil)
    end
  end

  proxy
end

#uniq!Object



63
64
65
66
# File 'lib/libxml/ext/uniq_mixin.rb', line 63

def uniq!
  @_uniq = true
  self
end

#uniq?Boolean

Returns:

  • (Boolean)


68
69
70
# File 'lib/libxml/ext/uniq_mixin.rb', line 68

def uniq?
  @_uniq
end