Class: Slimmer::TagMover

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

Instance Method Summary collapse

Instance Method Details

#filter(src, dest) ⇒ Object



178
179
180
181
182
# File 'lib/slimmer.rb', line 178

def filter(src,dest)
  move_tags(src, dest, 'script', :must_have => ['src'])
  move_tags(src, dest, 'link',   :must_have => ['href'])
  move_tags(src, dest, 'meta',   :must_have => ['name', 'content'], :keys => ['name', 'content', 'http-equiv'])
end

#include_tag?(node, min_attrs) ⇒ Boolean

Returns:

  • (Boolean)


184
185
186
# File 'lib/slimmer.rb', line 184

def include_tag?(node, min_attrs)
  min_attrs.inject(true) { |all_okay, attr_name| all_okay && node.has_attribute?(attr_name) }
end

#move_tags(src, dest, type, opts) ⇒ Object



194
195
196
197
198
199
200
201
202
203
204
205
206
207
# File 'lib/slimmer.rb', line 194

def move_tags(src, dest, type, opts)
  comparison_attrs = opts[:keys] || opts[:must_have]
  min_attrs = opts[:must_have]
  already_there = dest.css(type).map { |node|
    tag_fingerprint(node, comparison_attrs)
  }.compact

  src.css(type).each do |node|
    if include_tag?(node, min_attrs) && !already_there.include?(tag_fingerprint(node, comparison_attrs))
      node.remove
      dest.at_xpath('/html/head') << node
    end
  end
end

#tag_fingerprint(node, attrs) ⇒ Object



188
189
190
191
192
# File 'lib/slimmer.rb', line 188

def tag_fingerprint(node, attrs)
  attrs.collect do |attr_name|
    node.has_attribute?(attr_name) ? node.attr(attr_name) : nil
  end.compact.sort
end