Class: Slimmer::Processors::BodyInserter

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

Instance Method Summary collapse

Constructor Details

#initialize(source_id = "wrapper", destination_id = "wrapper", headers = {}) ⇒ BodyInserter

Returns a new instance of BodyInserter.



3
4
5
6
7
# File 'lib/slimmer/processors/body_inserter.rb', line 3

def initialize(source_id = "wrapper", destination_id = "wrapper", headers = {})
  @source_selector = "##{source_id}"
  @destination_selector = "##{destination_id}"
  @headers = headers
end

Instance Method Details

#filter(src, dest) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/slimmer/processors/body_inserter.rb', line 9

def filter(src, dest)
  source_markup = src.at_css(@source_selector)
  destination_markup = dest.at_css(@destination_selector)

  if source_markup.nil?
    raise(Slimmer::SourceWrapperNotFoundError, <<~ERROR_MESSAGE, caller)
      Slimmer did not find a div with ID "wrapper" in the source HTML.
      This could be because a request was made to your Rails application
      for a format that it does not support. For example a JavaScript request,
      when the application only has HTML templates.
    ERROR_MESSAGE
  end

  css_classes = []
  css_classes << source_markup.attributes["class"].to_s.split(/ +/) if source_markup.has_attribute?("class")
  css_classes << destination_markup.attributes["class"].to_s.split(/ +/) if destination_markup.has_attribute?("class")

  body = Nokogiri::HTML.fragment(source_markup.to_html)
  dest.at_css(@destination_selector).replace(body)
  dest.at_css(@destination_selector).set_attribute("class", css_classes.flatten.uniq.join(" ")) if is_gem_layout? && css_classes.any?
end