Module: Simplabs::Highlight::ViewMethods

Defined in:
lib/simplabs/highlight.rb

Overview

View Helpers for using Simplabs::Highlight in Ruby on Rails templates.

Instance Method Summary collapse

Instance Method Details

#highlight_code(language, code = nil) { ... } ⇒ String

Highlights the passed code with the appropriate rules according to the specified language. The code can be specified either as a string or provided in a block.

Examples:

Specifying the code to highlight as a String


highlight_code(:ruby, 'class Test; end')

Specifying the code to highlight in a block


highlight_code(:ruby) do
  klass = 'class'
  name  = 'Test'
  _end  = 'end'
  "#{klass} #{name}; #{_end}"
end

Parameters:

  • language (Symbol, String)

    the language the code is in

  • code (String) (defaults to: nil)

    the actual code to highlight

Yields:

  • the code can also be specified as result of a given block.

Returns:

  • (String)

    the highlighted code or simply the HTML-escaped code if language is not supported.

Raises:

  • (ArgumentError)

    if both the code parameter and a block are given

  • (ArgumentError)

    if neither the code parameter or a block are given

See Also:



162
163
164
165
166
167
# File 'lib/simplabs/highlight.rb', line 162

def highlight_code(language, code = nil, &block)
  raise ArgumentError.new('Either pass a srting containing the code or a block, not both!') if !code.nil? && block_given?
  raise ArgumentError.new('Pass a srting containing the code or a block!') if code.nil? && !block_given?
  code ||= yield
  Simplabs::Highlight.highlight(language, code)
end