Module: Pygmalion

Defined in:
lib/pygmalion.rb

Defined Under Namespace

Modules: ClassMethods

Constant Summary collapse

PYGMALION_HOST =
'pygments.com'
PYGMALION_JSON_PATH =
"/json/"
PYGMALION_PUSH_PATH =
"/push_chunk/"
PYGMALION_CHUNK_SIZE =
4000
PYGMALION_CHUNK_REGEX =
Regexp.new(".{1,#{PYGMALION_CHUNK_SIZE}}", Regexp::MULTILINE)
PYGMALION_DEFAULTS =
{
  :css => 'n',
  :id => 'pygmalion',
  :linenos => 'off'
}

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.included(base) ⇒ Object



20
21
22
# File 'lib/pygmalion.rb', line 20

def self.included(base)
  base.extend ClassMethods
end

Instance Method Details

#highlight(options = {}) ⇒ Object

return a syntax-highlighted version of the string

options:

line_numbers: boolean indicating whether or not to include line numbers language: language to use for highlighting



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/pygmalion.rb', line 46

def highlight(options = {})
  # strip out options needing translation
  line_numbers = options.delete(:line_numbers)
  language = options.delete(:language)

  # merge provided options into the defaults
  options = PYGMALION_DEFAULTS.merge(options)

  # translate the aforementioned options
  options[:linenos] = line_numbers ? 'on' : 'off'
  options[:type] = language
  
  res = Net::HTTP::start(PYGMALION_HOST) do |http|
    if self.size <= PYGMALION_CHUNK_SIZE
      # if code is small enough, use a single request
      http.get self.class.pygments_query(options, self)
    else
      # otherwise break into chunks and push to the server
      headers = {}
      self.scan(PYGMALION_CHUNK_REGEX).each_with_index do |chunk, chunkid|
        # TODO: try threads for potential speedup with multiple simultaneous requests if this proves too slow
        response = http.get self.class.pygments_query(options, chunk, chunkid), headers
        # the server uses a cookie-based session to deal with chunked requests
        headers['cookie'] = response['set-cookie'] if response['set-cookie']
      end
      # get the final response once all chunks are processed
      http.get self.class.pygments_query(options), headers
    end
  end
  
  ActiveSupport::JSON.decode(res.body[/\{.*\}/m])['output']
end