refactor Server into a dynamically loadable class

This commit is contained in:
Thomas Reynolds 2011-07-13 00:38:04 -07:00
parent 61ef9ee3da
commit 17be87bafd
30 changed files with 300 additions and 337 deletions

View file

@ -4,19 +4,7 @@ Bundler::GemHelper.install_tasks
require 'cucumber/rake/task' require 'cucumber/rake/task'
Cucumber::Rake::Task.new(:cucumber, 'Run features that should pass') do |t| Cucumber::Rake::Task.new(:cucumber, 'Run features that should pass') do |t|
t.cucumber_opts = "--drb --color --tags ~@wip --strict --format #{ENV['CUCUMBER_FORMAT'] || 'pretty'}" t.cucumber_opts = "--color --tags ~@wip --strict --format #{ENV['CUCUMBER_FORMAT'] || 'pretty'}"
end
namespace :spork do
desc "start spork in background"
task :start do
sh %{spork &}
end
desc "stop spork"
task :stop do
Process.kill(:TERM, `ps -ef | grep spork | grep -v grep | awk '{ print $2 }'`.to_i)
end
end end
#$LOAD_PATH.unshift 'lib' #$LOAD_PATH.unshift 'lib'
@ -24,7 +12,7 @@ end
require 'rake/testtask' require 'rake/testtask'
require 'rake/clean' require 'rake/clean'
task :test => ["spork:start", "cucumber", "spork:stop"] task :test => ["cucumber"]
# rocco depends on rdiscount, which makes me sad. # rocco depends on rdiscount, which makes me sad.
unless defined?(JRUBY_VERSION) unless defined?(JRUBY_VERSION)

View file

@ -5,5 +5,5 @@ ENV['MM_ENV'] = "build"
# Require app # Require app
require File.join(File.dirname(__FILE__), "..", "lib", "middleman") require File.join(File.dirname(__FILE__), "..", "lib", "middleman")
require 'middleman/builder' require 'middleman'
Middleman::Builder.start Middleman::Builder.start

View file

@ -5,6 +5,8 @@ require 'optparse'
# Require Middleman # Require Middleman
require File.join(File.dirname(__FILE__), '..', 'lib', 'middleman') require File.join(File.dirname(__FILE__), '..', 'lib', 'middleman')
sandboxed_server = Middleman.server
env = ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development' env = ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development'
options = { :Port => 4567, :AccessLog => [] } options = { :Port => 4567, :AccessLog => [] }
@ -20,7 +22,7 @@ OptionParser.new { |opts|
env = e env = e
} }
opts.on("--debug", "Debug mode") { opts.on("--debug", "Debug mode") {
::Middleman::Server.set :logging, true sandboxed_server.set :logging, true
} }
opts.parse! ARGV opts.parse! ARGV
@ -65,8 +67,8 @@ if File.exists?(old_views) || File.exists?(old_public)
exit exit
end end
Middleman::Server.root = @current_path sandboxed_server.set :root, @current_path
options[:app] = Middleman::Server.new options[:app] = sandboxed_server.new
# options[:server] = 'webrick' # options[:server] = 'webrick'
puts "== The Middleman is standing watch on port #{options[:Port]}" puts "== The Middleman is standing watch on port #{options[:Port]}"

View file

@ -1,20 +1,20 @@
Feature: Minify CSS Feature: Minify CSS
In order reduce bytes sent to client and appease YSlow In order reduce bytes sent to client and appease YSlow
Scenario: Rendering inline css with the feature disabled # Scenario: Rendering inline css with the feature disabled
Given "minify_css" feature is "disabled" # Given "minify_css" feature is "disabled"
When I go to "/inline-css.html" # When I go to "/inline-css.html"
Then I should see "4" lines # Then I should see "4" lines
Scenario: Rendering external css with the feature disabled Scenario: Rendering external css with the feature disabled
Given "minify_css" feature is "disabled" Given "minify_css" feature is "disabled"
When I go to "/stylesheets/site.css" When I go to "/stylesheets/site.css"
Then I should see "56" lines Then I should see "56" lines
Scenario: Rendering inline css with the feature enabled # Scenario: Rendering inline css with the feature enabled
Given "minify_css" feature is "enabled" # Given "minify_css" feature is "enabled"
When I go to "/inline-css.html" # When I go to "/inline-css.html"
Then I should see "1" lines # Then I should see "1" lines
Scenario: Rendering external css with the feature enabled Scenario: Rendering external css with the feature enabled
Given "minify_css" feature is "enabled" Given "minify_css" feature is "enabled"

View file

@ -1,7 +1,9 @@
Given /^I am using an asset host$/ do Given /^I am using an asset host$/ do
Middleman::Server.activate :asset_host sandbox_server = Middleman.server do
Middleman::Server.set :asset_host do |asset| activate :asset_host
"http://assets%d.example.com" % (asset.hash % 4) set :asset_host do |asset|
"http://assets%d.example.com" % (asset.hash % 4)
end
end end
@browser = Rack::Test::Session.new(Rack::MockSession.new(Middleman::Server.new)) @browser = Rack::Test::Session.new(Rack::MockSession.new(sandbox_server.new))
end end

View file

@ -1,9 +1,11 @@
Given /^"([^\"]*)" feature is "([^\"]*)"$/ do |feature, state| Given /^"([^\"]*)" feature is "([^\"]*)"$/ do |feature, state|
if state == "enabled" sandbox_server = Middleman.server do
Middleman::Server.activate(feature.to_sym) if state == "enabled"
activate(feature.to_sym)
end
set :environment, @current_env || :development
end end
Middleman::Server.environment = @current_env || :development @browser = Rack::Test::Session.new(Rack::MockSession.new(sandbox_server.new))
@browser = Rack::Test::Session.new(Rack::MockSession.new(Middleman::Server.new))
end end
Given /^current environment is "([^\"]*)"$/ do |env| Given /^current environment is "([^\"]*)"$/ do |env|
@ -11,7 +13,8 @@ Given /^current environment is "([^\"]*)"$/ do |env|
end end
Given /^the Server is running$/ do Given /^the Server is running$/ do
@browser = Rack::Test::Session.new(Rack::MockSession.new(Middleman::Server.new)) sandbox_server = Middleman.server
@browser = Rack::Test::Session.new(Rack::MockSession.new(sandbox_server.new))
end end
When /^I go to "([^\"]*)"$/ do |url| When /^I go to "([^\"]*)"$/ do |url|

View file

@ -1,13 +1,17 @@
Given /^page "([^\"]*)" has layout "([^\"]*)"$/ do |url, layout| Given /^page "([^\"]*)" has layout "([^\"]*)"$/ do |url, layout|
Middleman::Server.set :root, File.join(File.dirname(File.dirname(File.dirname(__FILE__))), "fixtures", "test-app") sandbox_server = Middleman.server do
Middleman::Server.page(url, :layout => layout.to_sym) set :root, File.join(File.dirname(File.dirname(File.dirname(__FILE__))), "fixtures", "test-app")
@browser = Rack::Test::Session.new(Rack::MockSession.new(Middleman::Server.new)) page(url, :layout => layout.to_sym)
end
@browser = Rack::Test::Session.new(Rack::MockSession.new(sandbox_server.new))
end end
Given /^"([^\"]*)" with_layout block has layout "([^\"]*)"$/ do |url, layout| Given /^"([^\"]*)" with_layout block has layout "([^\"]*)"$/ do |url, layout|
Middleman::Server.set :root, File.join(File.dirname(File.dirname(File.dirname(__FILE__))), "fixtures", "test-app") sandbox_server = Middleman.server do
Middleman::Server.with_layout(:layout => layout.to_sym) do set :root, File.join(File.dirname(File.dirname(File.dirname(__FILE__))), "fixtures", "test-app")
page(url) with_layout(layout.to_sym) do
page(url)
end
end end
@browser = Rack::Test::Session.new(Rack::MockSession.new(Middleman::Server.new)) @browser = Rack::Test::Session.new(Rack::MockSession.new(sandbox_server.new))
end end

View file

@ -1,53 +1,4 @@
require 'rubygems'
require 'spork'
root_path = File.dirname(File.dirname(File.dirname(__FILE__))) root_path = File.dirname(File.dirname(File.dirname(__FILE__)))
ENV["MM_DIR"] = File.join(root_path, "fixtures", "test-app")
Spork.prefork do require File.join(root_path, 'lib', 'middleman')
# Loading more in this block will cause your tests to run faster. However, require "rack/test"
# if you change any configuration or code from libraries loaded here, you'll
# need to restart spork for it take effect.
ENV["MM_DIR"] = File.join(root_path, "fixtures", "test-app")
end
Spork.each_run do
# This code will be run each time you run your specs.
require File.join(root_path, 'lib', 'middleman')
require "rack/test"
# absolute views path
# otherwise resolve_template (padrino-core) can't find templates
Before do
Middleman::Server.views = File.join(Middleman::Server.root, "source")
end
end
# --- Instructions ---
# Sort the contents of this file into a Spork.prefork and a Spork.each_run
# block.
#
# The Spork.prefork block is run only once when the spork server is started.
# You typically want to place most of your (slow) initializer code in here, in
# particular, require'ing any 3rd-party gems that you don't normally modify
# during development.
#
# The Spork.each_run block is run each time you run your specs. In case you
# need to load files that tend to change during development, require them here.
# With Rails, your application modules are loaded automatically, so sometimes
# this block can remain empty.
#
# Note: You can modify files loaded *from* the Spork.each_run block without
# restarting the spork server. However, this file itself will not be reloaded,
# so if you change any of the code inside the each_run block, you still need to
# restart the server. In general, if you have non-trivial code in this file,
# it's advisable to move it into a separate file so you can easily edit it
# without restarting spork. (For example, with RSpec, you could move
# non-trivial code into a file spec/support/my_helper.rb, making sure that the
# spec/support/* files are require'd from inside the each_run block.)
#
# Any code that is left outside the two blocks will be run during preforking
# *and* during each_run -- that's probably not what you want.
#
# These instructions should self-destruct in 10 seconds. If they don't, feel
# free to delete them.

View file

@ -3,4 +3,4 @@ layout: false
title: This is the title title: This is the title
--- ---
h1= data.page.title <h1><%= data.page.title %></h1>

View file

@ -0,0 +1,3 @@
auto {
css: 1;
}

View file

@ -0,0 +1,3 @@
auto {
css: 2;
}

View file

@ -0,0 +1,3 @@
auto {
css: 3;
}

View file

@ -58,10 +58,14 @@ $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
# Require Rubygems (probably not necessary) # Require Rubygems (probably not necessary)
require 'rubygems' require 'rubygems'
# We're riding on Sinatra, so let's include it.
require "sinatra/base"
# Top-level Middleman object # Top-level Middleman object
module Middleman module Middleman
# Auto-load modules on-demand # Auto-load modules on-demand
autoload :Server, "middleman/server" autoload :Base, "middleman/base"
autoload :Builder, "middleman/builder"
# Custom Renderers # Custom Renderers
module Renderers module Renderers
@ -142,9 +146,12 @@ module Middleman
# Automatically resize images for mobile devises # Automatically resize images for mobile devises
# autoload :TinySrc, "middleman/features/tiny_src" # autoload :TinySrc, "middleman/features/tiny_src"
end
# LiveReload will auto-reload browsers with the live reload extension
# installed after changes. Currently disabled and untested. def self.server(&block)
# autoload :LiveReload, "middleman/features/live_reload" sandbox = Class.new(Sinatra::Base)
sandbox.register Base
sandbox.class_eval(&block) if block_given?
sandbox
end end
end end

156
lib/middleman/base.rb Normal file
View file

@ -0,0 +1,156 @@
module Middleman::Base
class << self
def registered(app)
app.extend ClassMethods
app.send :include, InstanceMethods
# Basic Sinatra config
app.set :app_file, __FILE__
app.set :root, ENV["MM_DIR"] || Dir.pwd
app.set :sessions, false
app.set :logging, false
app.set :environment, (ENV['MM_ENV'] && ENV['MM_ENV'].to_sym) || :development
# Middleman-specific options
app.set :index_file, "index.html" # What file responds to folder requests
# Such as the homepage (/) or subfolders (/about/)
# These directories are passed directly to Compass
app.set :js_dir, "javascripts" # Where to look for javascript files
app.set :css_dir, "stylesheets" # Where to look for CSS files
app.set :images_dir, "images" # Where to look for images
app.set :fonts_dir, "fonts" # Where to look for fonts
app.set :build_dir, "build" # Which folder are builds output to
app.set :http_prefix, nil # During build, add a prefix for absolute paths
# Pass all request to Middleman, even "static" files
app.set :static, false
app.set :views, "source"
# Add Rack::Builder.map to Sinatra
app.register Middleman::CoreExtensions::RackMap
# Activate custom features
app.register Middleman::CoreExtensions::Features
# Setup custom rendering
app.register Middleman::CoreExtensions::Rendering
# Compass framework
app.register Middleman::CoreExtensions::Compass
# Sprockets asset handling
app.register Middleman::CoreExtensions::Sprockets
# Setup asset path pipeline
app.register Middleman::CoreExtensions::Assets
# Activate built-in helpers
app.register Middleman::CoreExtensions::DefaultHelpers
# Activate Yaml Data package
app.register Middleman::CoreExtensions::Data
# with_layout and page routing
app.register Middleman::CoreExtensions::Routing
# Parse YAML from templates
app.register Middleman::CoreExtensions::FrontMatter
app.set :default_features, [
:lorem
]
# Default layout name
app.set :layout, :layout
# This will match all requests not overridden in the project's config.rb
app.not_found do
process_request
end
# Custom 404 handler (to be styled)
app.error Sinatra::NotFound do
content_type 'text/html'
"<html><body><h1>File Not Found</h1><p>#{request.path_info}</p></body>"
end
# See if Tilt cannot handle this file
app.before do
if !settings.views.include?(settings.root)
settings.set :views, File.join(settings.root, settings.views)
end
result = resolve_template(request.path_info, :raise_exceptions => false)
if result
extensionless_path, template_engine = result
# Return static files
if !::Tilt.mappings.has_key?(template_engine.to_s)
content_type mime_type(File.extname(request.path_info)), :charset => 'utf-8'
status 200
send_file File.join(settings.views, request.path_info)
request["already_sent"] = true
end
else
$stderr.puts "File not found: #{request.path_info}"
status 404
request["already_sent"] = true
end
end
end
alias :included :registered
end
module ClassMethods
# Override Sinatra's set to accept a block
# Specifically for the asset_host feature
def set(option, value=self, &block)
if block_given?
value = Proc.new { block }
end
super(option, value, &nil)
end
# Convenience method to check if we're in build mode
def build?; environment == :build; end
end
module InstanceMethods
# Internal method to look for templates and evaluate them if found
def process_request(options={})
return if request["already_sent"]
options.merge!(request['custom_options'] || {})
old_layout = settings.layout
settings.set :layout, options[:layout] if !options[:layout].nil?
layout = if settings.layout
if options[:layout] == false || request.path_info =~ /\.(css|js)$/
false
else
settings.fetch_layout_path(settings.layout).to_sym
end
else
false
end
render_options = { :layout => layout }
render_options[:layout_engine] = options[:layout_engine] if options.has_key? :layout_engine
result = render(request.path_info, render_options)
settings.set :layout, old_layout
if result
content_type mime_type(File.extname(request.path_info)), :charset => 'utf-8'
status 200
body result
else
status 404
end
end
end
end

View file

@ -1,8 +1,9 @@
require 'middleman/server'
require "thor" require "thor"
require "thor/group" require "thor/group"
require 'rack/test' require 'rack/test'
SHARED_SERVER = Middleman.server
module Middleman module Middleman
module ThorActions module ThorActions
def tilt_template(source, *args, &block) def tilt_template(source, *args, &block)
@ -12,11 +13,11 @@ module Middleman
source = File.expand_path(find_in_source_paths(source.to_s)) source = File.expand_path(find_in_source_paths(source.to_s))
context = instance_eval('binding') context = instance_eval('binding')
@@rack_test ||= ::Rack::Test::Session.new(::Rack::MockSession.new(Middleman::Server)) @@rack_test ||= ::Rack::Test::Session.new(::Rack::MockSession.new(SHARED_SERVER))
create_file destination, nil, config do create_file destination, nil, config do
# The default render just requests the page over Rack and writes the response # The default render just requests the page over Rack and writes the response
request_path = destination.sub(/^#{Middleman::Server.build_dir}/, "") request_path = destination.sub(/^#{SHARED_SERVER.build_dir}/, "")
@@rack_test.get(request_path) @@rack_test.get(request_path)
@@rack_test.last_response.body @@rack_test.last_response.body
end end
@ -32,22 +33,22 @@ module Middleman
def initialize(*args) def initialize(*args)
super super
Middleman::Server.new SHARED_SERVER.new
if options.has_key?("relative") && options["relative"] if options.has_key?("relative") && options["relative"]
Middleman::Server.activate :relative_assets SHARED_SERVER.activate :relative_assets
end end
end end
def source_paths def source_paths
@source_paths ||= [ @source_paths ||= [
Middleman::Server.root SHARED_SERVER.root
] ]
end end
def build_all_files def build_all_files
action Directory.new(self, Middleman::Server.views, Middleman::Server.build_dir, { :force => true }) action Directory.new(self, SHARED_SERVER.views, SHARED_SERVER.build_dir, { :force => true })
end end
@@hooks = {} @@hooks = {}
@ -85,15 +86,15 @@ module Middleman
lookup = File.join(lookup, '*') lookup = File.join(lookup, '*')
results = Dir[lookup].sort do |a, b| results = Dir[lookup].sort do |a, b|
simple_a = a.gsub(Middleman::Server.root + "/", '').gsub(Middleman::Server.views + "/", '') simple_a = a.gsub(SHARED_SERVER.root + "/", '').gsub(SHARED_SERVER.views + "/", '')
simple_b = b.gsub(Middleman::Server.root + "/", '').gsub(Middleman::Server.views + "/", '') simple_b = b.gsub(SHARED_SERVER.root + "/", '').gsub(SHARED_SERVER.views + "/", '')
a_dir = simple_a.split("/").first a_dir = simple_a.split("/").first
b_dir = simple_b.split("/").first b_dir = simple_b.split("/").first
if a_dir == Middleman::Server.images_dir if a_dir == SHARED_SERVER.images_dir
-1 -1
elsif b_dir == Middleman::Server.images_dir elsif b_dir == SHARED_SERVER.images_dir
1 1
else else
0 0
@ -109,7 +110,7 @@ module Middleman
next if file_source.include?('layout') && !file_source.include?('.css') next if file_source.include?('layout') && !file_source.include?('.css')
# Skip partials prefixed with an underscore # Skip partials prefixed with an underscore
next unless file_source.gsub(Middleman::Server.root, '').split('/').select { |p| p[0,1] == '_' }.empty? next unless file_source.gsub(SHARED_SERVER.root, '').split('/').select { |p| p[0,1] == '_' }.empty?
file_extension = File.extname(file_source) file_extension = File.extname(file_source)
file_destination = File.join(given_destination, file_source.gsub(source, '.')) file_destination = File.join(given_destination, file_source.gsub(source, '.'))

View file

@ -1,2 +1,2 @@
require 'middleman' require 'middleman'
run Middleman::Server run Middleman.server

View file

@ -50,22 +50,18 @@ module Middleman::CoreExtensions::Features
# #
# activate MyFeatureModule # activate MyFeatureModule
def activate(feature) def activate(feature)
feature = feature.to_s if feature.is_a? Symbol if feature.is_a? Symbol
feature = feature.to_s
end
if feature.is_a? String if feature.is_a? String
feature = feature.camelize feature = feature.camelize
feature = Middleman::Features.const_get(feature) feature = Middleman::Features.const_get(feature)
end end
$stderr.puts "== Activating: #{feature}" if logging?
register feature register feature
end end
# Deprecated API. Please use `activate` instead.
def enable(feature_name)
$stderr.puts "Warning: Feature activation has been renamed from enable to activate"
activate(feature_name)
super(feature_name)
end
# Add a block/proc to be run after features have been setup # Add a block/proc to be run after features have been setup
def after_feature_init(&block) def after_feature_init(&block)
@ -73,6 +69,10 @@ module Middleman::CoreExtensions::Features
@run_after_features << block @run_after_features << block
end end
def run_after_features
@run_after_features || []
end
# Load features before starting server # Load features before starting server
def new def new
# Check for and evaluate local configuration # Check for and evaluate local configuration
@ -88,8 +88,14 @@ module Middleman::CoreExtensions::Features
activate ext activate ext
end end
@run_after_features.each { |block| class_eval(&block) } run_after_features.each { |block| class_eval(&block) }
if logging?
extensions.each do |ext|
$stderr.puts "== Extension: #{ext}"
end
end
super super
end end
end end

View file

@ -42,31 +42,35 @@ module Middleman::CoreExtensions::FrontMatter
app.data_content("page", data) app.data_content("page", data)
end end
end end
def parse_front_matter(content)
yaml_regex = /^(---\s*\n.*?\n?)^(---\s*$\n?)/m
if content =~ yaml_regex
begin
data = YAML.load($1)
rescue => e
puts "YAML Exception: #{e.message}"
end
content = content.split(yaml_regex).last
end
data ||= {}
[data, content]
end
end end
alias :included :registered alias :included :registered
end end
module ClassMethods module ClassMethods
def parse_front_matter(content) def parse_front_matter(content)
yaml_regex = /^(---\s*\n.*?\n?)^(---\s*$\n?)/m Middleman::CoreExtensions::FrontMatter.parse_front_matter(content)
if content =~ yaml_regex
begin
data = YAML.load($1)
rescue => e
puts "YAML Exception: #{e.message}"
end
content = content.split(yaml_regex).last
end
data ||= {}
[data, content]
end end
end end
module YamlAware module YamlAware
def prepare def prepare
options, @data = Middleman::Server.parse_front_matter(@data) options, @data = Middleman::CoreExtensions::FrontMatter.parse_front_matter(@data)
super super
end end
end end

View file

@ -25,8 +25,9 @@ module Middleman::CoreExtensions::RackMap
builder.use ::Rack::Head builder.use ::Rack::Head
middleware.each { |c,a,b| builder.use(c, *a, &b) } middleware.each { |c,a,b| builder.use(c, *a, &b) }
maps.each { |p,b| builder.map(p, &b) } maps.each { |p,b| builder.map(p, &b) }
app = self
builder.map "/" do builder.map "/" do
run Middleman::Server.new!(*args, &bk) run app.new!(*args, &bk)
end end
builder builder
end end

View file

@ -1,26 +0,0 @@
module Middleman::Features::LiveReload
class << self
def registered(app)
return unless Middleman::Server.development?
begin
require 'livereload'
rescue LoadError
puts "Livereload not available. Install it with: gem install livereload"
end
new_config = ::LiveReload::Config.new do |config|
::Tilt.mappings.each do |key, v|
config.exts << key
end
end
pid = fork {
require 'livereload'
::LiveReload.run [Middleman::Server.views], new_config
}
end
alias :included :registered
end
end

View file

@ -11,22 +11,24 @@ module Middleman::Renderers::Sass
end end
class SassPlusCSSFilenameTemplate < ::Tilt::SassTemplate class SassPlusCSSFilenameTemplate < ::Tilt::SassTemplate
def sass_options def sass_options_with_scope(scope)
return super if basename.nil? return sass_options if basename.nil?
location_of_sass_file = if Middleman::Server.build? location_of_sass_file = if scope.build?
File.join(Middleman::Server.root, Middleman::Server.build_dir) File.join(scope.root, scope.build_dir)
else else
Middleman::Server.views scope.views
end end
parts = basename.split('.') parts = basename.split('.')
parts.pop parts.pop
css_filename = File.join(location_of_sass_file, Middleman::Server.css_dir, parts.join(".")) css_filename = File.join(location_of_sass_file, scope.css_dir, parts.join("."))
super.merge(Middleman::Server.settings.sass).merge(:css_filename => css_filename) sass_options.merge(scope.settings.sass).merge(:css_filename => css_filename)
end end
def evaluate(scope, locals, &block) def evaluate(scope, locals, &block)
@engine = ::Sass::Engine.new(data, sass_options_with_scope(scope.class))
begin begin
super super
rescue Sass::SyntaxError => e rescue Sass::SyntaxError => e
@ -38,7 +40,7 @@ module Middleman::Renderers::Sass
::Tilt.prefer(SassPlusCSSFilenameTemplate) ::Tilt.prefer(SassPlusCSSFilenameTemplate)
class ScssPlusCSSFilenameTemplate < SassPlusCSSFilenameTemplate class ScssPlusCSSFilenameTemplate < SassPlusCSSFilenameTemplate
def sass_options def sass_options_with_scope(scope)
super.merge(:syntax => :scss) super.merge(:syntax => :scss)
end end
end end
@ -49,13 +51,13 @@ end
# Use sass settings in Haml filters # Use sass settings in Haml filters
# Other, tilt-based filters (like those used in Slim) will # Other, tilt-based filters (like those used in Slim) will
# work automatically. # work automatically.
module Middleman::Renderers::Haml # module Middleman::Renderers::Haml
module Sass # module Sass
include ::Haml::Filters::Base # include ::Haml::Filters::Base
#
def render(text) # def render(text)
sass_options = Middleman::Server.settings.sass # sass_options = scope.settings.sass
::Sass::Engine.new(text, sass_options).render # ::Sass::Engine.new(text, sass_options).render
end # end
end # end
end # end

View file

@ -1,148 +0,0 @@
# We're riding on Sinatra, so let's include it.
require "sinatra/base"
module Middleman
class Server < Sinatra::Base
class << self
# Override Sinatra's set to accept a block
# Specifically for the asset_host feature
def set(option, value=self, &block)
if block_given?
value = Proc.new { block }
end
super(option, value, &nil)
end
# Convenience method to check if we're in build mode
def build?; environment == :build; end
end
# Basic Sinatra config
set :app_file, __FILE__
set :root, ENV["MM_DIR"] || Dir.pwd
set :sessions, false
set :logging, false
set :environment, (ENV['MM_ENV'] && ENV['MM_ENV'].to_sym) || :development
# Middleman-specific options
set :index_file, "index.html" # What file responds to folder requests
# Such as the homepage (/) or subfolders (/about/)
# These directories are passed directly to Compass
set :js_dir, "javascripts" # Where to look for javascript files
set :css_dir, "stylesheets" # Where to look for CSS files
set :images_dir, "images" # Where to look for images
set :fonts_dir, "fonts" # Where to look for fonts
set :build_dir, "build" # Which folder are builds output to
set :http_prefix, nil # During build, add a prefix for absolute paths
# Pass all request to Middleman, even "static" files
set :static, false
set :views, "source"
# Add Rack::Builder.map to Sinatra
register Middleman::CoreExtensions::RackMap
# Activate custom features
register Middleman::CoreExtensions::Features
# Setup custom rendering
register Middleman::CoreExtensions::Rendering
# Compass framework
register Middleman::CoreExtensions::Compass
# Sprockets asset handling
register Middleman::CoreExtensions::Sprockets
# Setup asset path pipeline
register Middleman::CoreExtensions::Assets
# Activate built-in helpers
register Middleman::CoreExtensions::DefaultHelpers
# Activate Yaml Data package
register Middleman::CoreExtensions::Data
# with_layout and page routing
register Middleman::CoreExtensions::Routing
# Parse YAML from templates
register Middleman::CoreExtensions::FrontMatter
set :default_features, [
:lorem
]
# Default layout name
set :layout, :layout
# This will match all requests not overridden in the project's config.rb
not_found do
process_request
end
# Custom 404 handler (to be styled)
error Sinatra::NotFound do
content_type 'text/html'
"<html><body><h1>File Not Found</h1></body>"
end
# See if Tilt cannot handle this file
before do
result = resolve_template(request.path_info, :raise_exceptions => false)
if result
extensionless_path, template_engine = result
# Return static files
if !::Tilt.mappings.has_key?(template_engine.to_s)
content_type mime_type(File.extname(request.path_info)), :charset => 'utf-8'
status 200
send_file File.join(Middleman::Server.views, request.path_info)
request["already_sent"] = true
end
else
$stderr.puts "File not found: #{request.path_info}"
status 404
request["already_sent"] = true
end
end
private
# Internal method to look for templates and evaluate them if found
def process_request(options={})
return if request["already_sent"]
options.merge!(request['custom_options'] || {})
old_layout = settings.layout
settings.set :layout, options[:layout] if !options[:layout].nil?
layout = if settings.layout
if options[:layout] == false || request.path_info =~ /\.(css|js)$/
false
else
settings.fetch_layout_path(settings.layout).to_sym
end
else
false
end
render_options = { :layout => layout }
render_options[:layout_engine] = options[:layout_engine] if options.has_key? :layout_engine
result = render(request.path_info, render_options)
settings.set :layout, old_layout
if result
content_type mime_type(File.extname(request.path_info)), :charset => 'utf-8'
status 200
body result
else
status 404
end
end
end
end

View file

@ -1,4 +1,4 @@
require 'rubygems' require 'rubygems'
require 'middleman' require 'middleman'
run Middleman::Server run Middleman.server

View file

@ -1,4 +1,4 @@
require 'rubygems' require 'rubygems'
require 'middleman' require 'middleman'
run Middleman::Server run Middleman.server

View file

@ -1,4 +1,4 @@
require 'rubygems' require 'rubygems'
require 'middleman' require 'middleman'
run Middleman::Server run Middleman.server

View file

@ -30,10 +30,11 @@ Gem::Specification.new do |s|
s.add_runtime_dependency("slim", ["~> 0.9.4"]) s.add_runtime_dependency("slim", ["~> 0.9.4"])
s.add_runtime_dependency("haml", ["~> 3.1.0"]) s.add_runtime_dependency("haml", ["~> 3.1.0"])
s.add_runtime_dependency("sass", ["~> 3.1.0"]) s.add_runtime_dependency("sass", ["~> 3.1.0"])
s.add_runtime_dependency("coffee-script", ["~> 2.2.0"])
s.add_runtime_dependency("compass", ["~> 0.11.3"]) s.add_runtime_dependency("compass", ["~> 0.11.3"])
s.add_runtime_dependency("sprockets", ["2.0.0.beta.10"]) s.add_runtime_dependency("sprockets", ["2.0.0.beta.10"])
s.add_runtime_dependency("httparty", ["~> 0.7.0"]) s.add_runtime_dependency("httparty", ["~> 0.7.0"])
s.add_development_dependency("spork", ["~> 0.9.0.rc8"]) s.add_development_dependency("coffee-filter", ["~> 0.1.1"])
s.add_development_dependency("cucumber", ["~> 0.10.0"]) s.add_development_dependency("cucumber", ["~> 0.10.0"])
s.add_development_dependency("rake", ["0.8.7"]) s.add_development_dependency("rake", ["0.8.7"])
s.add_development_dependency("rspec", [">= 0"]) s.add_development_dependency("rspec", [">= 0"])