Module: Gumdrop

Defined in:
lib/gumdrop.rb,
lib/gumdrop/cli.rb,
lib/gumdrop/data.rb,
lib/gumdrop/site.rb,
lib/gumdrop/server.rb,
lib/gumdrop/builder.rb,
lib/gumdrop/content.rb,
lib/gumdrop/version.rb,
lib/gumdrop/renderer.rb,
lib/gumdrop/generator.rb,
lib/gumdrop/util/loggable.rb,
lib/gumdrop/util/view_helpers.rb,
lib/gumdrop/util/proxy_handler.rb

Overview

require ‘ostruct’

Defined Under Namespace

Modules: CLI, Data, Support, Util Classes: Builder, Content, ContentList, DataManager, Generator, RenderContext, Renderer, Server, Site, SpecialContentList

Constant Summary collapse

WEB_PAGE_EXTS =
%w(.html .htm)
JETSAM_FILES =
%w(**/.DS_Store .git* .git/**/* .svn/**/* **/.sass-cache/**/* Gumdrop)
DEFAULT_CONFIG =
{
  relative_paths: true,
  relative_paths_exts: WEB_PAGE_EXTS,
  default_layout: 'site',
  layout_exts: WEB_PAGE_EXTS,
  proxy_enabled: false,
  output_dir: "./output",
  source_dir: "./source",
  data_dir: './data',
  log: STDOUT,
  log_level: :info,
  ignore: JETSAM_FILES,
  blacklist: [],
  server_timeout: 5,
  server_port: 4567,
  env: :production,
  file_change_test: :checksum
}
STATIC_ASSETS =
%w(.jpg .jpe .jpeg .gif .ico .png .swf)
VERSION =
"1.0.2"
LOG_LEVELS =
{
    debug: Logger::DEBUG,
     info: Logger::INFO,
     warn: Logger::WARN,
    error: Logger::ERROR,
    fatal: Logger::FATAL,
  unknown: Logger::UNKNOWN
}

Class Method Summary collapse

Class Method Details

.blacklist(*paths) ⇒ Object

Specified paths will not be renderd to output (matching against the source tree).



323
324
325
326
327
328
329
330
331
# File 'lib/gumdrop/site.rb', line 323

def blacklist(*paths)
  paths.each do |path|
    if path.is_a? Array
      config.blacklist.concat path
    else
      config.blacklist << path
    end
  end      
end

.build(opts = {}) ⇒ Object



143
144
145
146
147
# File 'lib/gumdrop/builder.rb', line 143

def build(opts={})
  opts= opts.to_symbolized_hash
  site.scan
  Builder.new(opts).execute
end

.change_logObject

Returns ‘ReadMe.md’ from gem package.



35
36
37
38
# File 'lib/gumdrop.rb', line 35

def self.change_log
  here= File.dirname(__FILE__)
  File.read here / ".." / "ChangeLog.md"
end

.cli(&block) ⇒ Object

Allows addition of CLI commands from Gumdrop file:

Gumdrop.cli do
  desc 'ping'
  method_option :loud, default:false
  def ping
    say options[:loud] ? 'PONG!' : 'pong'
  end
end


15
16
17
# File 'lib/gumdrop/cli.rb', line 15

def cli(&block)
  CLI::Internal.class_eval &block
end

.configObject

Short cut to the current Site config object.



288
289
290
# File 'lib/gumdrop/site.rb', line 288

def config
  site.config
end

.configure(&block) ⇒ Object

Yield a configuration object. You can update Gumdrop behavior as well as add your own config information.



283
284
285
# File 'lib/gumdrop/site.rb', line 283

def configure(&block)
  site.configure &block
end

.envObject

The env Gumdrop is run in – You can set this in the congig or, better, via command line: ‘gumdrop build -e test`



294
295
296
# File 'lib/gumdrop/site.rb', line 294

def env
  site.env
end

.generate(name = nil, opts = {}, &block) ⇒ Object

Generate a page (based on data or whatever) from your Gumdrop file like this:

Gumdrop.generate 'label' do |gen|
  gen.file 'my-page.html' do
    # whatever you return is set as the page contents.
    "hello!"
  end
end


139
140
141
142
# File 'lib/gumdrop/generator.rb', line 139

def generate(name=nil, opts={}, &block)
  opts[:filename]= name unless opts[:filename]
  site.generators << Generator.new(nil, opts, &block)
end

.handle_proxy(proxy, proxy_url, env) ⇒ Object



26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
# File 'lib/gumdrop/util/proxy_handler.rb', line 26

def self.handle_proxy(proxy, proxy_url, env)
  if proxy[:secure] && !HTTPS_ENABLED
    log.warn "~ WARNING: HTTPS is not supported on your system, using HTTP instead.\n"
    log.warn "   If you are using Ubuntu, you can run `apt-get install libopenssl-ruby`\n"
    proxy[:secure] = false
  end

  origin_host = env['SERVER_NAME'] # capture the origin host for cookies
  http_method = env['REQUEST_METHOD'].to_s.downcase
  url = proxy[:path_info] #proxy_url #env['PATH_INFO']
  params = env['QUERY_STRING']
  
  log.info "PROXY: -> #{url}"

  # collect headers...
  headers = {}
  env.each do |key, value|
    next unless key =~ /^HTTP_/
    key = key.gsub(/^HTTP_/,'').downcase.sub(/^\w/){|l| l.upcase}.gsub(/_(\w)/){|l| "-#{$1.upcase}"} # remove HTTP_, dasherize and titleize
    if !key.eql? "Version"
      headers[key] = value
    end
  end

  # Rack documentation says CONTENT_TYPE and CONTENT_LENGTH aren't prefixed by HTTP_
  headers['Content-Type'] = env['CONTENT_TYPE'] if env['CONTENT_TYPE']

  length = env['CONTENT_LENGTH']
  headers['Content-Length'] = length if length

  http_host, http_port = proxy[:to].split(':')
  http_port = proxy[:secure] ? '443' : '80' if http_port.nil?

  # added 4/23/09 per Charles Jolley, corrects problem
  # when making requests to virtual hosts
  headers['Host'] = "#{http_host}:#{http_port}"

  if proxy[:url]
    url = url.sub(/^#{Regexp.escape proxy_url}/, proxy[:url])
  end

  http_path = [url]
  http_path << params if params && params.size>0
  http_path = http_path.join('?')

  response = nil
  no_body_method = %w(get copy head move options trace)

  done = false
  tries = 0
  until done
    http = ::Net::HTTP.new(http_host, http_port)

    if proxy[:secure]
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end

    http.start do |web|
      if no_body_method.include?(http_method)
        response = web.send(http_method, http_path, headers)
      else
        http_body = env['rack.input']
        http_body.rewind # May not be necessary but can't hurt

        req = Net::HTTPGenericRequest.new(http_method.upcase,
                                            true, true, http_path, headers)
        req.body_stream = http_body if length.to_i > 0
        response = web.request(req)
      end
    end

    status = response.code # http status code
    protocol = proxy[:secure] ? 'https' : 'http'

    log.log "~ PROXY: #{http_method.upcase} #{status} #{url} -> #{protocol}://#{http_host}:#{http_port}#{http_path}\n"

    # display and construct specific response headers
    response_headers = {}
    ignore_headers = ['transfer-encoding', 'keep-alive', 'connection']
    response.each do |key, value|
      next if ignore_headers.include?(key.downcase)
      # If this is a cookie, strip out the domain.  This technically may
      # break certain scenarios where services try to set cross-domain
      # cookies, but those services should not be doing that anyway...
      value.gsub!(/domain=[^\;]+\;? ?/,'') if key.downcase == 'set-cookie'
      # Location headers should rewrite the hostname if it is included.
      value.gsub!(/^http:\/\/#{http_host}(:[0-9]+)?\//, "http://#{http_host}/") if key.downcase == 'location'
      # content-length is returning char count not bytesize
      if key.downcase == 'content-length'
        if response.body.respond_to?(:bytesize)
          value = response.body.bytesize.to_s
        elsif response.body.respond_to?(:size)
          value = response.body.size.to_s
        else
          value = '0'
        end
      end

      #$stderr << "   #{key}: #{value}\n"

      response_headers[key] = value
    end

    if [301, 302, 303, 307].include?(status.to_i) && proxy[:redirect] != false
      log.warn '~ REDIRECTING: '+response_headers['location']+"\n"

      uri = URI.parse(response_headers['location']);
      http_host = uri.host
      http_port = uri.port
      http_path = uri.path
      http_path += '?'+uri.query if uri.query

      tries += 1
      if tries > 10
        raise "Too many redirects!"
      end
    else
      done = true
    end
  end

  # Thin doesn't like null bodies
  response_body = response.body || ''
  #::Rack::Utils::HeaderHash.new(response_headers)
  return [status.to_i, response_headers, response_body.to_s]
end

.ignore(*paths) ⇒ Object

Specified paths will be added to the ignore list, preventing matching files from appearing in the source tree



311
312
313
314
315
316
317
318
319
# File 'lib/gumdrop/site.rb', line 311

def ignore(*paths)
  paths.each do |path|
    if path.is_a? Array
      config.ignore.concat path
    else
      config.ignore << path
    end
  end      
end

.in_site_folder?(filename = "Gumdrop") ⇒ Boolean

Returns true if this, or a parent, folder has a Gumdrop file.

Returns:

  • (Boolean)


305
306
307
# File 'lib/gumdrop/site.rb', line 305

def in_site_folder?(filename="Gumdrop")
  !fetch_site_file(filename).nil?
end

.init_loggingObject



32
33
34
35
36
37
38
39
40
# File 'lib/gumdrop/util/loggable.rb', line 32

def init_logging
  level= (site.config.log_level || :warn).to_sym
  @log = Logger.new site.config.log || STDOUT
  @log.level=  LOG_LEVELS[level]
  # @log.formatter = proc { |severity, datetime, progname, msg|
  #   # original_formatter.call(severity, datetime, progname, msg.dump)
  #   "#{msg}\n"
  # }
end

.logObject



24
25
26
27
28
29
30
# File 'lib/gumdrop/util/loggable.rb', line 24

def log
  @log ||= begin
    log= Logger.new STDOUT
    log.level= LOG_LEVELS[:warn]
    log
  end
end

.modeObject

Mostly for internal use, but you can update/change it in the configure block.



300
301
302
# File 'lib/gumdrop/site.rb', line 300

def mode
  site.mode
end

.on(event_type, options = {}, &block) ⇒ Object

Listen for life-cycle events in your Gumdrop file like this:

Gumdrop.on :start do |event|
  puts "Here we go!"
end

Complete list of events fired by Gumdrop:

:start
:before_scan
:scan
:after_scan
:before_generate
:generate
:after_generate
:before_generate_item
:generate_item
:after_generate_item
:before_build
:build
:after_build
:before_checksum
:checksum
:after_checksum
:before_render
:render
:after_render
:before_render_item
:render_item
:after_render_item
:before_write
:write
:after_write
:before_copy_file
:copy_file
:after_copy_file
:before_write_file
:write_file
:after_write_file
:end

In the block parem ‘event` you will have access to :site, the current executing site instance, and :payload, where applicable.

:render_item is a special event because you can add/override the compiled output by modifying ‘event.data.return_value`



277
278
279
# File 'lib/gumdrop/site.rb', line 277

def on(event_type, options={}, &block)
  site.on event_type, options, &block
end

.rebuildObject



149
150
151
152
# File 'lib/gumdrop/builder.rb', line 149

def rebuild
  site.scan true
  Builder.new.execute
end

.run(opts = {}) ⇒ Object

Kicks off the build process!



155
156
157
158
159
# File 'lib/gumdrop/builder.rb', line 155

def run(opts={})
  opts= opts.to_symbolized_hash
  site.options= opts
  Gumdrop.build opts
end

.site(opts = {}, force_new = false) ⇒ Object

This will look for a nearby Gumdrop file and load the Site the first time it is called. Each time after it will just return the already created Site.



215
216
217
218
219
220
221
222
223
224
225
226
227
228
# File 'lib/gumdrop/site.rb', line 215

def site(opts={}, force_new=false)
  opts= opts.to_symbolized_hash
  unless @current_site.nil? or force_new
    @current_site.options= opts unless opts.empty?
    @current_site
  else
    site_file= fetch_site_file
    unless site_file.nil?
      Site.new site_file, opts
    else
      nil
    end
  end
end

.view_helpers(&block) ⇒ Object



45
46
47
# File 'lib/gumdrop/util/view_helpers.rb', line 45

def view_helpers(&block)
  Util::ViewHelpers.class_eval &block
end