Module: Shaven::NokogiriExt::Node

Included in:
Nokogiri::XML::Node
Defined in:
lib/shaven/nokogiri_ext/node.rb

Constant Summary collapse

UJS_DATA_ATTRIBUTES =

List of extra data-* attributes for dealing with unobtrusive javascript stuff. Following attributes will be converted to html compilant attrs. The true and false values here means if attribute is boolean or not.

{ 
  'remote'  => true, 
  'confirm' => false, 
  'method'  => false 
}

Instance Method Summary collapse

Instance Method Details

#replace!(text_or_node = nil, &block) ⇒ Object

Helper for replacing current node with other text or node.

Example

node.replace!(other_node)
node.replace!("Text")
node.replace! { "Something new" }

XXX: replace/replace_node method failed with segfault so this is some workaround…



57
58
59
60
61
62
63
64
65
66
67
# File 'lib/shaven/nokogiri_ext/node.rb', line 57

def replace!(text_or_node=nil, &block)
  text_or_node = block.call if block_given?
  
  unless text_or_node.nokogiri_node?
    content, text_or_node = text_or_node.to_s, Nokogiri::XML::Text.new("dummy", document)
    text_or_node.content = content
  end
  
  node = add_previous_sibling(text_or_node)
  remove
end

#update!(attrs = {}, content = nil, &block) ⇒ Object

Helper for easy updating node’s attributes and content.

Example

node.update!(:id => "hello-world").to_html # => <div id="hello-world"></div>
node.update!(nil, "Foo!").to_html          # => <div id="hello-world">Foo!</div>
node.update! { "Foobar!" }                 # => <div id="hello-world">Foobar!</div>
node.update!(:id => false)                 # => <div>Foobar!</div>


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/shaven/nokogiri_ext/node.rb', line 22

def update!(attrs={}, content=nil, &block)
  attrs = {} unless attrs
  attrs = apply_ujs_data_attributes(attrs.stringify_keys)
  
  # Applying attributes...
  attrs.each { |key,value|
    if value === false
      delete(key.to_s)
    else
      self[key.to_s] = value.to_s
    end
  }

  content = block.call if block_given?
  
  # Applying content...
  if content.is_a?(Nokogiri::XML::Node)
    self.inner_html = content
  elsif !content.nil?
    self.content = content.to_s
  end

  return self
end