class Integral::ContentRenderer

Handles the rendering of dynamic content (Widgets) within static HTML A widget could be used to list recent articles from the blog, featured content from a list, etc

Example Widget Markup <p class='integral-widget' data-widget-type='recent_posts' data-widget-value-tagged='sweet-tag'>

Constants

PLACEHOLDER_SELECTOR

Markup defining a widget

Public Class Methods

render(raw_html) click to toggle source

Renders WYSIWYG html, converting any widget placeholders to dynamic content

@param raw_html [String]

@return [String] Parsed content

# File lib/integral/content_renderer.rb, line 26
def self.render(raw_html)
  html = Nokogiri::HTML(raw_html)
  html.css(self::PLACEHOLDER_SELECTOR).each do |placeholder|
    widget_type = placeholder.attributes['data-widget-type']&.value

    placeholder.replace(render_widget(widget_type, widget_options(placeholder.attributes)))
  end

  html.css('body').inner_html.html_safe
end
render_widget(type, options) click to toggle source

Renders a specific widget using the provided options

@param type [String] Type of widget to render @param options [Hash] Widget options to use when rendering

@return [String] widget content

# File lib/integral/content_renderer.rb, line 56
def self.render_widget(type, options)
  widget = widgets.find { |w| w[0] == type }

  return widget_not_available_message unless widget.present?

  widget[1].constantize.render(options)
rescue StandardError => e
  respond_with_widget_error(e)
end
respond_with_widget_error(error) click to toggle source

Handles widget errors

# File lib/integral/content_renderer.rb, line 67
def self.respond_with_widget_error(error)
  Rails.logger.error(error.message)

  '<!-- Error rendering widget -->'
end
widget_not_available_message() click to toggle source

@return [String] Widget not available message

# File lib/integral/content_renderer.rb, line 74
def self.widget_not_available_message
  '<!-- Widget not available -->'
end
widget_options(placeholder_attributes) click to toggle source

Parse placeholder attributes to find any widget options

@param placeholder_attributes [Hash] raw placeholder attributes

@return [Hash] widget options

# File lib/integral/content_renderer.rb, line 42
def self.widget_options(placeholder_attributes)
  options = {}
  keys = placeholder_attributes.keys.select { |key| key.starts_with?('data-widget-value-') }

  keys.each { |key| options[key.remove('data-widget-value-').to_sym] = placeholder_attributes[key].value }
  options
end
widgets() click to toggle source

@return [Array] available widgets used to render dynamic content

# File lib/integral/content_renderer.rb, line 12
def self.widgets
  widgets = [
    ['recent_posts', 'Integral::Widgets::RecentPosts'],
    ['swiper_list', 'Integral::Widgets::SwiperList']
  ]

  widgets.concat Integral.additional_widgets
end