class Prismic::Fragments::StructuredText

Attributes

blocks[RW]

Public Class Methods

new(blocks) click to toggle source
# File lib/prismic/fragments/structured_text.rb, line 22
def initialize(blocks)
  @blocks = blocks
end

Public Instance Methods

as_html(link_resolver, html_serializer=nil) click to toggle source

Serializes the current StructuredText fragment into a fully usable HTML code. You need to pass a proper link_resolver so that internal links are turned into the proper URL in your website. If you use a starter kit, one is provided, that you can still update later.

This method simply executes the as_html methods on blocks; it is not advised to override this method if you want to change the HTML output, you should override the as_html method at the block level (like {Heading.as_html}, or {Preformatted.as_html}, for instance). @param link_resolver [LinkResolver] @param html_serializer [HtmlSerializer] @return [String] the resulting html snippet

# File lib/prismic/fragments/structured_text.rb, line 38
def as_html(link_resolver, html_serializer=nil)
  # Defining blocks that deserve grouping, assigning them "group kind" names
  block_group = ->(block){
    case block
    when Block::ListItem
      block.ordered? ? "ol" : "ul"
    else
      nil
    end
  }
  # Initializing groups, which is an array of BlockGroup objects
  groups, last = [], nil
  blocks.each {|block|
    group = block_group.(block)
    groups << BlockGroup.new(group) if !last || group != last
    groups.last << block
    last = group
  }
  # HTML-serializing the groups object (delegating the serialization of Block objects),
  # without forgetting to frame the BlockGroup objects right if needed
  groups.map{|group|
    html = group.blocks.map { |b|
      b.as_html(link_resolver, html_serializer)
    }.join
    case group.kind
    when "ol"
      %(<ol>#{html}</ol>)
    when "ul"
      %(<ul>#{html}</ul>)
    else
      html
    end
  }.join("\n\n")
end
as_text(separator=' ') click to toggle source

Returns the StructuredText as plain text, with zero formatting. Non-textual blocks (like images and embeds) are simply ignored.

@param separator [String] The string separator inserted between the blocks (a blank space by default) @return [String] The complete string representing the textual value of the StructuredText field.

# File lib/prismic/fragments/structured_text.rb, line 78
def as_text(separator=' ')
  blocks.map{|block| block.as_text }.compact.join(separator)
end
first_title() click to toggle source

Finds the first highest title in a structured text

# File lib/prismic/fragments/structured_text.rb, line 83
def first_title
  max_level = 6 # any title with a higher level kicks the current one out
  title = false
  @blocks.each do |block|
    if block.is_a?(Prismic::Fragments::StructuredText::Block::Heading)
      if block.level < max_level
        title = block.text
        max_level = block.level # new maximum
      end
    end
  end
  title
end