Skip to content

Instantly share code, notes, and snippets.

@monnoval
Last active August 29, 2015 13:58
Show Gist options
  • Save monnoval/9951870 to your computer and use it in GitHub Desktop.
Save monnoval/9951870 to your computer and use it in GitHub Desktop.
Middleman - Add domain after build, can also be used as a search and replace after build
class AddDomain
def initialize(app, options={})
@app = app
@options = options
end
def call(env)
status, headers, response = @app.call(env)
if env['PATH_INFO'].end_with?('.html')
content = ::Middleman::Util.extract_response_text(response)
deploy_to_url = @options[:url]
updated_content = content.
gsub("href=\"\/","href=\"#{deploy_to_url}").
gsub("&body=\/","&body=#{deploy_to_url}").
gsub("&body=\/","&body=#{deploy_to_url}").
gsub(/^( |\t)+/, "").
each_line.reject{|x| x.strip == ""}.join
headers['Content-Length'] = ::Rack::Utils.bytesize(updated_content).to_s
response = [updated_content]
end
[status, headers, response]
end
end
require 'adddomain'
configure :build do
use AddDomain, :url => "http://google.com/"
end
@tdreyno
Copy link

tdreyno commented Apr 3, 2014

Could also be accomplished as Rack middleware:

class AddDomain
  def initialize(app, options={})
    @app = app
    @options = options
  end

  def call(env)
    status, headers, response = @app.call(env)

    if env['PATH_INFO'].end_with?('.html')
      content = ::Middleman::Util.extract_response_text(response)

      deploy_to_url = @options[:url]

      updated_content = content.
                          gsub("href=\"\/","href=\"#{deploy_to_url}").
                          gsub("&body=\/","&body=#{deploy_to_url}").
                          gsub("&body=\/","&body=#{deploy_to_url}").
                          gsub(/^( |\t)+/, "").
                          each_line.reject{|x| x.strip == ""}.join

      headers['Content-Length'] = ::Rack::Utils.bytesize(updated_content).to_s
      response = [updated_content]
    end

    [status, headers, response]
  end
end

configure :build do
  use AddDomain, :url => "http://google.com"
end

@monnoval
Copy link
Author

monnoval commented May 5, 2014

Updated to run as rack middleware. Thanks @tdreyno !

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment