Implemented Rubocop

- just took a stab at running the StringLiterals cop to get a taste.
This commit is contained in:
Karl Freeman 2013-12-28 00:26:31 +00:00
parent e996868033
commit 03d6e6c990
80 changed files with 510 additions and 477 deletions

25
.rubocop.yml Normal file
View file

@ -0,0 +1,25 @@
AllCops:
Includes:
- Rakefile
- config.ru
Excludes:
- script/**
- vendor/**
- bin/**
- middleman-core/lib/vendored-middleman-deps/**
- middleman-core/bin/**
- middleman-core/fixtures/**
- middleman-core/features/**
- middleman-core/spec/**
LineLength:
Enabled: false
MethodLength:
Enabled: false
ClassLength:
Enabled: false
Documentation:
Enabled: false
Encoding:
Enabled: false
HashSyntax:
EnforcedStyle: ruby19

View file

@ -34,6 +34,7 @@ end
# Code Quality # Code Quality
gem "cane", :platforms => [:mri_19, :mri_20], :require => false gem "cane", :platforms => [:mri_19, :mri_20], :require => false
gem 'coveralls', :require => false gem 'coveralls', :require => false
gem 'rubocop', :require => false
# Middleman itself # Middleman itself
gem "middleman-core", :path => "middleman-core" gem "middleman-core", :path => "middleman-core"

View file

@ -2,7 +2,7 @@ require 'rubygems' unless defined?(Gem)
# require 'fileutils' unless defined?(FileUtils) # require 'fileutils' unless defined?(FileUtils)
require 'rake' require 'rake'
require File.expand_path("../middleman-core/lib/middleman-core/version.rb", __FILE__) require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__)
ROOT = File.expand_path(File.dirname(__FILE__)) ROOT = File.expand_path(File.dirname(__FILE__))
GEM_NAME = 'middleman' GEM_NAME = 'middleman'
@ -26,26 +26,26 @@ task :install do
end end
end end
desc "Clean pkg and other stuff" desc 'Clean pkg and other stuff'
task :clean do task :clean do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
%w[tmp pkg coverage].each { |dir| sh 'rm -rf %s' % File.join(g, dir) } %w[tmp pkg coverage].each { |dir| sh 'rm -rf %s' % File.join(g, dir) }
end end
end end
desc "Clean pkg and other stuff" desc 'Clean pkg and other stuff'
task :uninstall do task :uninstall do
sh "gem search --no-version middleman | grep middleman | xargs gem uninstall -a" sh 'gem search --no-version middleman | grep middleman | xargs gem uninstall -a'
end end
desc "Displays the current version" desc 'Displays the current version'
task :version do task :version do
say "Current version: #{Middleman::VERSION}" say "Current version: #{Middleman::VERSION}"
end end
desc "Bumps the version number based on given version" desc 'Bumps the version number based on given version'
task :bump, [:version] do |t, args| task :bump, [:version] do |t, args|
raise "Please specify version=x.x.x !" unless args.version raise 'Please specify version=x.x.x !' unless args.version
version_path = File.dirname(__FILE__) + '/middleman-core/lib/middleman-core/version.rb' version_path = File.dirname(__FILE__) + '/middleman-core/lib/middleman-core/version.rb'
version_text = File.read(version_path).sub(/VERSION = '[\d\.\w]+'/, "VERSION = '#{args.version}'") version_text = File.read(version_path).sub(/VERSION = '[\d\.\w]+'/, "VERSION = '#{args.version}'")
say "Updating Middleman to version #{args.version}" say "Updating Middleman to version #{args.version}"
@ -53,41 +53,41 @@ task :bump, [:version] do |t, args|
sh 'git commit -a -m "Bumped version to %s"' % args.version sh 'git commit -a -m "Bumped version to %s"' % args.version
end end
desc "Executes a fresh install removing all middleman version and then reinstall all gems" desc 'Executes a fresh install removing all middleman version and then reinstall all gems'
task :fresh => [:uninstall, :install, :clean] task :fresh => [:uninstall, :install, :clean]
desc "Pushes repository to GitHub" desc 'Pushes repository to GitHub'
task :push do task :push do
say "Pushing to github..." say 'Pushing to github...'
sh "git tag v#{Middleman::VERSION}" sh "git tag v#{Middleman::VERSION}"
sh "git push origin master" sh 'git push origin master'
sh "git push origin v#{Middleman::VERSION}" sh "git push origin v#{Middleman::VERSION}"
end end
desc "Release all middleman gems" desc 'Release all middleman gems'
task :publish => :push do task :publish => :push do
say "Pushing to rubygems..." say 'Pushing to rubygems...'
GEM_PATHS.each do |dir| GEM_PATHS.each do |dir|
Dir.chdir(dir) { sh_rake("release") } Dir.chdir(dir) { sh_rake('release') }
end end
Rake::Task["clean"].invoke Rake::Task['clean'].invoke
end end
desc "Generate documentation for all middleman gems" desc 'Generate documentation for all middleman gems'
task :doc do task :doc do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake yard" } Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake yard" }
end end
end end
desc "Run tests for all middleman gems" desc 'Run tests for all middleman gems'
task :test do task :test do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" } Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" }
end end
end end
desc "Run specs for all middleman gems" desc 'Run specs for all middleman gems'
task :spec do task :spec do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake spec" } Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake spec" }
@ -96,16 +96,23 @@ end
begin begin
require 'cane/rake_task' require 'cane/rake_task'
desc 'Run cane to check quality metrics'
desc "Run cane to check quality metrics"
Cane::RakeTask.new(:quality) do |cane| Cane::RakeTask.new(:quality) do |cane|
cane.no_style = true cane.no_style = true
cane.no_doc = true cane.no_doc = true
cane.abc_glob = "middleman*/lib/middleman*/**/*.rb" cane.abc_glob = 'middleman*/lib/middleman*/**/*.rb'
end end
rescue LoadError rescue LoadError
# warn "cane not available, quality task not provided."
end end
desc "Run tests for all middleman gems" begin
require 'rubocop/rake_task'
desc 'Run RuboCop to check code consistency'
Rubocop::RakeTask.new(:rubocop) do |task|
task.fail_on_error = false
end
rescue LoadError
end
desc 'Run tests for all middleman gems'
task :default => :test task :default => :test

View file

@ -17,30 +17,30 @@ end
require 'cucumber/rake/task' require 'cucumber/rake/task'
Cucumber::Rake::Task.new do |t| Cucumber::Rake::Task.new do |t|
exempt_tags = ["--tags ~@wip"] exempt_tags = ['--tags ~@wip']
exempt_tags << "--tags ~@nojava" if RUBY_PLATFORM == "java" exempt_tags << '--tags ~@nojava' if RUBY_PLATFORM == 'java'
exempt_tags << "--tags ~@encoding" unless Object.const_defined?(:Encoding) exempt_tags << '--tags ~@encoding' unless Object.const_defined?(:Encoding)
exempt_tags << "--tags ~@travishatesme" if ENV["TRAVIS"] == "true" exempt_tags << '--tags ~@travishatesme' if ENV['TRAVIS'] == 'true'
t.cucumber_opts = "--color #{exempt_tags.join(" ")} --strict --format #{ENV['CUCUMBER_FORMAT'] || 'Fivemat'}" t.cucumber_opts = "--color #{exempt_tags.join(" ")} --strict --format #{ENV['CUCUMBER_FORMAT'] || 'Fivemat'}"
end end
Cucumber::Rake::Task.new(:cucumber_wip) do |t| Cucumber::Rake::Task.new(:cucumber_wip) do |t|
exempt_tags = ["--tags @wip"] exempt_tags = ['--tags @wip']
exempt_tags << "--tags ~@nojava" if RUBY_PLATFORM == "java" exempt_tags << '--tags ~@nojava' if RUBY_PLATFORM == 'java'
exempt_tags << "--tags ~@encoding" unless Object.const_defined?(:Encoding) exempt_tags << '--tags ~@encoding' unless Object.const_defined?(:Encoding)
t.cucumber_opts = "--color #{exempt_tags.join(" ")} --strict --format #{ENV['CUCUMBER_FORMAT'] || 'Fivemat'}" t.cucumber_opts = "--color #{exempt_tags.join(" ")} --strict --format #{ENV['CUCUMBER_FORMAT'] || 'Fivemat'}"
end end
require 'rspec/core/rake_task' require 'rspec/core/rake_task'
desc "Run RSpec" desc 'Run RSpec'
RSpec::Core::RakeTask.new do |spec| RSpec::Core::RakeTask.new do |spec|
spec.pattern = 'spec/**/*_spec.rb' spec.pattern = 'spec/**/*_spec.rb'
spec.rspec_opts = ['--color', '--format nested'] spec.rspec_opts = ['--color', '--format nested']
end end
desc "Run tests, both RSpec and Cucumber" desc 'Run tests, both RSpec and Cucumber'
task :test => [:spec, :cucumber] task :test => [:spec, :cucumber]
YARD::Rake::YardocTask.new YARD::Rake::YardocTask.new

View file

@ -1,7 +1,7 @@
# coding:utf-8 # coding:utf-8
RAKE_ROOT = __FILE__ RAKE_ROOT = __FILE__
GEM_NAME = ENV["NAME"] || "middleman-core" GEM_NAME = ENV['NAME'] || 'middleman-core'
require 'rubygems' require 'rubygems'
require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper') require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper')

View file

@ -10,7 +10,7 @@ module Middleman
end end
require "middleman-core/version" require 'middleman-core/version'
require "middleman-core/util" require 'middleman-core/util'
require "middleman-core/extensions" require 'middleman-core/extensions'
require "middleman-core/application" require 'middleman-core/application'

View file

@ -1,25 +1,25 @@
# Using Tilt for templating # Using Tilt for templating
require "tilt" require 'tilt'
# i18n Built-in # i18n Built-in
require "i18n" require 'i18n'
# Don't fail on invalid locale, that's not what our current # Don't fail on invalid locale, that's not what our current
# users expect. # users expect.
::I18n.config.enforce_available_locales = false ::I18n.config.enforce_available_locales = false
# Use ActiveSupport JSON # Use ActiveSupport JSON
require "active_support/json" require 'active_support/json'
require "active_support/core_ext/integer/inflections" require 'active_support/core_ext/integer/inflections'
require "active_support/core_ext/float/rounding" require 'active_support/core_ext/float/rounding'
# Simple callback library # Simple callback library
require "vendored-middleman-deps/hooks-0.2.0/lib/hooks" require 'vendored-middleman-deps/hooks-0.2.0/lib/hooks'
require "middleman-core/sitemap" require 'middleman-core/sitemap'
require "middleman-core/configuration" require 'middleman-core/configuration'
require "middleman-core/core_extensions" require 'middleman-core/core_extensions'
# Core Middleman Class # Core Middleman Class
module Middleman module Middleman
@ -51,7 +51,7 @@ module Middleman
# Root project directory (overwritten in middleman build/server) # Root project directory (overwritten in middleman build/server)
# @return [String] # @return [String]
def self.root def self.root
ENV["MM_ROOT"] || Dir.pwd ENV['MM_ROOT'] || Dir.pwd
end end
delegate :root, :to => :"self.class" delegate :root, :to => :"self.class"
@ -63,7 +63,7 @@ module Middleman
# Name of the source directory # Name of the source directory
# @return [String] # @return [String]
config.define_setting :source, "source", 'Name of the source directory' config.define_setting :source, 'source', 'Name of the source directory'
# Middleman environment. Defaults to :development, set to :build by the build process # Middleman environment. Defaults to :development, set to :build by the build process
# @return [String] # @return [String]
@ -71,7 +71,7 @@ module Middleman
# Which file should be used for directory indexes # Which file should be used for directory indexes
# @return [String] # @return [String]
config.define_setting :index_file, "index.html", 'Which file should be used for directory indexes' config.define_setting :index_file, 'index.html', 'Which file should be used for directory indexes'
# Whether to strip the index file name off links to directory indexes # Whether to strip the index file name off links to directory indexes
# @return [Boolean] # @return [Boolean]
@ -83,35 +83,35 @@ module Middleman
# Location of javascripts within source. # Location of javascripts within source.
# @return [String] # @return [String]
config.define_setting :js_dir, "javascripts", 'Location of javascripts within source' config.define_setting :js_dir, 'javascripts', 'Location of javascripts within source'
# Location of stylesheets within source. Used by Compass. # Location of stylesheets within source. Used by Compass.
# @return [String] # @return [String]
config.define_setting :css_dir, "stylesheets", 'Location of stylesheets within source' config.define_setting :css_dir, 'stylesheets', 'Location of stylesheets within source'
# Location of images within source. Used by HTML helpers and Compass. # Location of images within source. Used by HTML helpers and Compass.
# @return [String] # @return [String]
config.define_setting :images_dir, "images", 'Location of images within source' config.define_setting :images_dir, 'images', 'Location of images within source'
# Location of fonts within source. Used by Compass. # Location of fonts within source. Used by Compass.
# @return [String] # @return [String]
config.define_setting :fonts_dir, "fonts", 'Location of fonts within source' config.define_setting :fonts_dir, 'fonts', 'Location of fonts within source'
# Location of partials within source. Used by renderers. # Location of partials within source. Used by renderers.
# @return [String] # @return [String]
config.define_setting :partials_dir, "", 'Location of partials within source' config.define_setting :partials_dir, '', 'Location of partials within source'
# Location of layouts within source. Used by renderers. # Location of layouts within source. Used by renderers.
# @return [String] # @return [String]
config.define_setting :layouts_dir, "layouts", 'Location of layouts within source' config.define_setting :layouts_dir, 'layouts', 'Location of layouts within source'
# Where to build output files # Where to build output files
# @return [String] # @return [String]
config.define_setting :build_dir, "build", 'Where to build output files' config.define_setting :build_dir, 'build', 'Where to build output files'
# Default prefix for building paths. Used by HTML helpers and Compass. # Default prefix for building paths. Used by HTML helpers and Compass.
# @return [String] # @return [String]
config.define_setting :http_prefix, "/", 'Default prefix for building paths' config.define_setting :http_prefix, '/', 'Default prefix for building paths'
# Default layout name # Default layout name
# @return [String, Symbold] # @return [String, Symbold]
@ -119,7 +119,7 @@ module Middleman
# Default string encoding for templates and output. # Default string encoding for templates and output.
# @return [String] # @return [String]
config.define_setting :encoding, "utf-8", 'Default string encoding for templates and output' config.define_setting :encoding, 'utf-8', 'Default string encoding for templates and output'
# Should Padrino include CRSF tag # Should Padrino include CRSF tag
# @return [Boolean] # @return [Boolean]
@ -172,7 +172,7 @@ module Middleman
# Evaluate a passed block if given # Evaluate a passed block if given
instance_exec(&block) if block_given? instance_exec(&block) if block_given?
config[:source] = ENV["MM_SOURCE"] if ENV["MM_SOURCE"] config[:source] = ENV['MM_SOURCE'] if ENV['MM_SOURCE']
super super
end end

View file

@ -1,6 +1,6 @@
# Require thor since that's what the who CLI is built around # Require thor since that's what the who CLI is built around
require 'thor' require 'thor'
require "thor/group" require 'thor/group'
# CLI Module # CLI Module
module Middleman module Middleman
@ -12,18 +12,18 @@ module Middleman
class << self class << self
def start(*args) def start(*args)
# Change flag to a module # Change flag to a module
ARGV.unshift("help") if ARGV.delete("--help") ARGV.unshift('help') if ARGV.delete('--help')
# Default command is server # Default command is server
if ARGV[0] != "help" && (ARGV.length < 1 || ARGV.first.include?("-")) if ARGV[0] != 'help' && (ARGV.length < 1 || ARGV.first.include?('-'))
ARGV.unshift("server") ARGV.unshift('server')
end end
super super
end end
end end
desc "version", "Show version" desc 'version', 'Show version'
def version def version
require 'middleman-core/version' require 'middleman-core/version'
say "Middleman #{Middleman::VERSION}" say "Middleman #{Middleman::VERSION}"
@ -36,7 +36,7 @@ module Middleman
def help(meth = nil, subcommand = false) def help(meth = nil, subcommand = false)
if meth && !self.respond_to?(meth) if meth && !self.respond_to?(meth)
klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}") klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}")
klass.start(["-h", task].compact, :shell => self.shell) klass.start(['-h', task].compact, :shell => self.shell)
else else
list = [] list = []
Thor::Util.thor_classes_in(Middleman::Cli).each do |thor_class| Thor::Util.thor_classes_in(Middleman::Cli).each do |thor_class|
@ -44,7 +44,7 @@ module Middleman
end end
list.sort!{ |a,b| a[0] <=> b[0] } list.sort!{ |a,b| a[0] <=> b[0] }
shell.say "Tasks:" shell.say 'Tasks:'
shell.print_table(list, :ident => 2, :truncate => true) shell.print_table(list, :ident => 2, :truncate => true)
shell.say shell.say
end end
@ -62,10 +62,10 @@ module Middleman
klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}") klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}")
if klass.nil? if klass.nil?
tasks_dir = File.join(Dir.pwd, "tasks") tasks_dir = File.join(Dir.pwd, 'tasks')
if File.exists?(tasks_dir) if File.exists?(tasks_dir)
Dir[File.join(tasks_dir, "**/*_task.rb")].each { |f| require f } Dir[File.join(tasks_dir, '**/*_task.rb')].each { |f| require f }
klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}") klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}")
end end
end end
@ -82,9 +82,9 @@ module Middleman
end end
# Include the core CLI items # Include the core CLI items
require "middleman-core/cli/init" require 'middleman-core/cli/init'
require "middleman-core/cli/bundler" require 'middleman-core/cli/bundler'
require "middleman-core/cli/extension" require 'middleman-core/cli/extension'
require "middleman-core/cli/server" require 'middleman-core/cli/server'
require "middleman-core/cli/build" require 'middleman-core/cli/build'
require "middleman-core/cli/console" require 'middleman-core/cli/console'

View file

@ -1,11 +1,11 @@
require "middleman-core" require 'middleman-core'
require "fileutils" require 'fileutils'
require 'set' require 'set'
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# Alias "b" to "build" # Alias "b" to "build"
Base.map({ "b" => "build" }) Base.map({ 'b' => 'build' })
# The CLI Build class # The CLI Build class
class Build < Thor class Build < Thor
@ -18,14 +18,14 @@ module Middleman::Cli
namespace :build namespace :build
desc "build [options]", "Builds the static site for deployment" desc 'build [options]', 'Builds the static site for deployment'
method_option :clean, method_option :clean,
:type => :boolean, :type => :boolean,
:default => true, :default => true,
:desc => 'Remove orphaned files from build (--no-clean to disable)' :desc => 'Remove orphaned files from build (--no-clean to disable)'
method_option :glob, method_option :glob,
:type => :string, :type => :string,
:aliases => "-g", :aliases => '-g',
:default => nil, :default => nil,
:desc => 'Build a subset of the project' :desc => 'Build a subset of the project'
method_option :verbose, method_option :verbose,
@ -44,33 +44,33 @@ module Middleman::Cli
# Core build Thor command # Core build Thor command
# @return [void] # @return [void]
def build def build
if !ENV["MM_ROOT"] if !ENV['MM_ROOT']
raise Thor::Error, "Error: Could not find a Middleman project config, perhaps you are in the wrong folder?" raise Thor::Error, 'Error: Could not find a Middleman project config, perhaps you are in the wrong folder?'
end end
# Use Rack::Test for inspecting a running server for output # Use Rack::Test for inspecting a running server for output
require "rack" require 'rack'
require "rack/test" require 'rack/test'
require 'find' require 'find'
@debugging = Middleman::Cli::Base.respond_to?(:debugging) && Middleman::Cli::Base.debugging @debugging = Middleman::Cli::Base.respond_to?(:debugging) && Middleman::Cli::Base.debugging
self.had_errors = false self.had_errors = false
self.class.shared_instance(options["verbose"], options["instrument"]) self.class.shared_instance(options['verbose'], options['instrument'])
opts = {} opts = {}
opts[:glob] = options["glob"] if options.has_key?("glob") opts[:glob] = options['glob'] if options.has_key?('glob')
opts[:clean] = options["clean"] opts[:clean] = options['clean']
action BuildAction.new(self, opts) action BuildAction.new(self, opts)
self.class.shared_instance.run_hook :after_build, self self.class.shared_instance.run_hook :after_build, self
if self.had_errors && !self.debugging if self.had_errors && !self.debugging
msg = "There were errors during this build" msg = 'There were errors during this build'
unless options["verbose"] unless options['verbose']
msg << ", re-run with `middleman build --verbose` to see the full exception." msg << ', re-run with `middleman build --verbose` to see the full exception.'
end end
self.shell.say msg, :red self.shell.say msg, :red
end end
@ -134,7 +134,7 @@ module Middleman::Cli
base.remove_file f, :force => true base.remove_file f, :force => true
end end
Dir[@build_dir.join("**", "*")].select {|d| File.directory?(d) }.each do |d| Dir[@build_dir.join('**', '*')].select {|d| File.directory?(d) }.each do |d|
base.remove_file d, :force => true if directory_empty? d base.remove_file d, :force => true if directory_empty? d
end end
end end
@ -177,15 +177,15 @@ module Middleman::Cli
sort_order = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .ico .woff .otf .ttf .eot .js .css) sort_order = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .ico .woff .otf .ttf .eot .js .css)
# Pre-request CSS to give Compass a chance to build sprites # Pre-request CSS to give Compass a chance to build sprites
logger.debug "== Prerendering CSS" logger.debug '== Prerendering CSS'
@app.sitemap.resources.select do |resource| @app.sitemap.resources.select do |resource|
resource.ext == ".css" resource.ext == '.css'
end.each do |resource| end.each do |resource|
@rack.get(URI.escape(resource.destination_path)) @rack.get(URI.escape(resource.destination_path))
end end
logger.debug "== Checking for Compass sprites" logger.debug '== Checking for Compass sprites'
# Double-check for compass sprites # Double-check for compass sprites
@app.files.find_new_files((@source_dir + @app.images_dir).relative_path_from(@app.root_path)) @app.files.find_new_files((@source_dir + @app.images_dir).relative_path_from(@app.root_path))
@ -195,7 +195,7 @@ module Middleman::Cli
# find files in the build folder when it needs to generate sprites for the # find files in the build folder when it needs to generate sprites for the
# css files # css files
logger.debug "== Building files" logger.debug '== Building files'
resources = @app.sitemap.resources.sort_by do |r| resources = @app.sitemap.resources.sort_by do |r|
sort_order.index(r.ext) || 100 sort_order.index(r.ext) || 100
@ -222,7 +222,7 @@ module Middleman::Cli
end end
end end
::Middleman::Profiling.report("build") ::Middleman::Profiling.report('build')
end end
# Render a resource to a file. # Render a resource to a file.
@ -268,14 +268,14 @@ module Middleman::Cli
if base.debugging if base.debugging
raise e raise e
exit(1) exit(1)
elsif base.options["verbose"] elsif base.options['verbose']
base.shell.say response, :red base.shell.say response, :red
end end
end end
def binary_encode(string) def binary_encode(string)
if string.respond_to?(:force_encoding) if string.respond_to?(:force_encoding)
string.force_encoding("ascii-8bit") string.force_encoding('ascii-8bit')
end end
string string
end end

View file

@ -8,7 +8,7 @@ module Middleman::Cli
namespace :bundle namespace :bundle
desc "bundle", "Setup initial bundle", :hide => true desc 'bundle', 'Setup initial bundle', :hide => true
# The setup task # The setup task
def bundle def bundle
@ -23,11 +23,11 @@ module Middleman::Cli
namespace :upgrade namespace :upgrade
desc "upgrade", "Upgrade installed bundle" desc 'upgrade', 'Upgrade installed bundle'
# The upgrade task # The upgrade task
def upgrade def upgrade
inside(ENV["MM_ROOT"]) do inside(ENV['MM_ROOT']) do
run('bundle update')#, :capture => true) run('bundle update')#, :capture => true)
end end
end end
@ -35,6 +35,6 @@ module Middleman::Cli
# Map "u" to "upgrade" # Map "u" to "upgrade"
Base.map({ Base.map({
"u" => "upgrade" 'u' => 'upgrade'
}) })
end end

View file

@ -9,18 +9,18 @@ module Middleman::Cli
namespace :console namespace :console
desc "console [options]", "Start an interactive console in the context of your Middleman application" desc 'console [options]', 'Start an interactive console in the context of your Middleman application'
method_option :environment, method_option :environment,
:aliases => "-e", :aliases => '-e',
:default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development', :default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development',
:desc => "The environment Middleman will run under" :desc => 'The environment Middleman will run under'
method_option :verbose, method_option :verbose,
:type => :boolean, :type => :boolean,
:default => false, :default => false,
:desc => 'Print debug messages' :desc => 'Print debug messages'
def console def console
require "middleman-core" require 'middleman-core'
require "irb" require 'irb'
opts = { opts = {
:environment => options['environment'], :environment => options['environment'],

View file

@ -15,22 +15,22 @@ module Middleman::Cli
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]
def self.source_root def self.source_root
File.join(File.dirname(__FILE__), "..", "templates", "extension") File.join(File.dirname(__FILE__), '..', 'templates', 'extension')
end end
desc "extension [options]", "Create Middleman extension scaffold NAME" desc 'extension [options]', 'Create Middleman extension scaffold NAME'
# The extension task # The extension task
# @param [String] name # @param [String] name
def extension def extension
generate_gitignore! generate_gitignore!
template "Rakefile", File.join(name, "Rakefile") template 'Rakefile', File.join(name, 'Rakefile')
template "gemspec", File.join(name, "#{name}.gemspec") template 'gemspec', File.join(name, "#{name}.gemspec")
template "Gemfile", File.join(name, "Gemfile") template 'Gemfile', File.join(name, 'Gemfile')
template "lib/middleman_extension.rb", File.join(name, "lib", "middleman_extension.rb") template 'lib/middleman_extension.rb', File.join(name, 'lib', 'middleman_extension.rb')
template "lib/lib.rb", File.join(name, "lib", "#{name}.rb") template 'lib/lib.rb', File.join(name, 'lib', "#{name}.rb")
template "features/support/env.rb", File.join(name, "features", "support", "env.rb") template 'features/support/env.rb', File.join(name, 'features', 'support', 'env.rb')
empty_directory File.join(name, "fixtures") empty_directory File.join(name, 'fixtures')
end end
# Output a .gitignore file # Output a .gitignore file
@ -41,7 +41,7 @@ module Middleman::Cli
# @return [void] # @return [void]
def generate_gitignore! def generate_gitignore!
return unless options[:git] return unless options[:git]
copy_file "gitignore", File.join(name, ".gitignore") copy_file 'gitignore', File.join(name, '.gitignore')
end end
} }

View file

@ -1,4 +1,4 @@
require "middleman-core/templates" require 'middleman-core/templates'
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
@ -9,35 +9,35 @@ module Middleman::Cli
namespace :init namespace :init
desc "init NAME [options]", "Create new project NAME" desc 'init NAME [options]', 'Create new project NAME'
available_templates = ::Middleman::Templates.registered.keys.join(", ") available_templates = ::Middleman::Templates.registered.keys.join(', ')
method_option "template", method_option 'template',
:aliases => "-T", :aliases => '-T',
:default => "default", :default => 'default',
:desc => "Use a project template: #{available_templates}" :desc => "Use a project template: #{available_templates}"
method_option "css_dir", method_option 'css_dir',
# :default => "stylesheets", # :default => "stylesheets",
:desc => 'The path to the css files' :desc => 'The path to the css files'
method_option "js_dir", method_option 'js_dir',
# :default => "javascripts", # :default => "javascripts",
:desc => 'The path to the javascript files' :desc => 'The path to the javascript files'
method_option "images_dir", method_option 'images_dir',
# :default => "images", # :default => "images",
:desc => 'The path to the image files' :desc => 'The path to the image files'
method_option "rack", method_option 'rack',
:type => :boolean, :type => :boolean,
:default => false, :default => false,
:desc => 'Include a config.ru file' :desc => 'Include a config.ru file'
method_option "skip-gemfile", method_option 'skip-gemfile',
:type => :boolean, :type => :boolean,
:default => false, :default => false,
:desc => "Don't create a Gemfile" :desc => "Don't create a Gemfile"
method_option "skip-bundle", method_option 'skip-bundle',
:type => :boolean, :type => :boolean,
:aliases => "-B", :aliases => '-B',
:default => false, :default => false,
:desc => "Don't run bundle install" :desc => "Don't run bundle install"
method_option "skip-git", method_option 'skip-git',
:type => :boolean, :type => :boolean,
:default => false, :default => false,
:desc => 'Skip Git ignores and keeps' :desc => 'Skip Git ignores and keeps'
@ -60,8 +60,8 @@ module Middleman::Cli
# Map "i", "new" and "n" to "init" # Map "i", "new" and "n" to "init"
Base.map({ Base.map({
"i" => "init", 'i' => 'init',
"new" => "init", 'new' => 'init',
"n" => "init" 'n' => 'init'
}) })
end end

View file

@ -7,20 +7,20 @@ module Middleman::Cli
namespace :server namespace :server
desc "server [options]", "Start the preview server" desc 'server [options]', 'Start the preview server'
method_option :environment, method_option :environment,
:aliases => "-e", :aliases => '-e',
:default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development', :default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development',
:desc => "The environment Middleman will run under" :desc => 'The environment Middleman will run under'
method_option :host, method_option :host,
:type => :string, :type => :string,
:aliases => "-h", :aliases => '-h',
:default => "0.0.0.0", :default => '0.0.0.0',
:desc => "Bind to HOST address" :desc => 'Bind to HOST address'
method_option :port, method_option :port,
:aliases => "-p", :aliases => '-p',
:default => "4567", :default => '4567',
:desc => "The port Middleman will listen on" :desc => 'The port Middleman will listen on'
method_option :verbose, method_option :verbose,
:type => :boolean, :type => :boolean,
:default => false, :default => false,
@ -47,35 +47,35 @@ module Middleman::Cli
:desc => 'Force file watcher into polling mode' :desc => 'Force file watcher into polling mode'
method_option :latency, method_option :latency,
:type => :numeric, :type => :numeric,
:aliases => "-l", :aliases => '-l',
:default => 0.25, :default => 0.25,
:desc => 'Set file watcher latency, in seconds' :desc => 'Set file watcher latency, in seconds'
# Start the server # Start the server
def server def server
require "middleman-core" require 'middleman-core'
require "middleman-core/preview_server" require 'middleman-core/preview_server'
if !ENV["MM_ROOT"] if !ENV['MM_ROOT']
puts "== Could not find a Middleman project config.rb" puts '== Could not find a Middleman project config.rb'
puts "== Treating directory as a static site to be served" puts '== Treating directory as a static site to be served'
ENV["MM_ROOT"] = Dir.pwd ENV['MM_ROOT'] = Dir.pwd
ENV["MM_SOURCE"] = "" ENV['MM_SOURCE'] = ''
end end
params = { params = {
:port => options["port"], :port => options['port'],
:host => options["host"], :host => options['host'],
:environment => options["environment"], :environment => options['environment'],
:debug => options["verbose"], :debug => options['verbose'],
:instrumenting => options["instrument"], :instrumenting => options['instrument'],
:disable_watcher => options["disable_watcher"], :disable_watcher => options['disable_watcher'],
:reload_paths => options["reload_paths"], :reload_paths => options['reload_paths'],
:force_polling => options["force_polling"], :force_polling => options['force_polling'],
:latency => options["latency"] :latency => options['latency']
} }
puts "== The Middleman is loading" puts '== The Middleman is loading'
::Middleman::PreviewServer.start(params) ::Middleman::PreviewServer.start(params)
end end
end end
@ -85,5 +85,5 @@ module Middleman::Cli
end end
# Map "s" to "server" # Map "s" to "server"
Base.map({ "s" => "server" }) Base.map({ 's' => 'server' })
end end

View file

@ -156,7 +156,7 @@ module Middleman
def define_setting(key, default=nil, description=nil) def define_setting(key, default=nil, description=nil)
raise "Setting #{key} doesn't exist" if @finalized raise "Setting #{key} doesn't exist" if @finalized
raise "Setting #{key} already defined" if @settings.has_key?(key) raise "Setting #{key} already defined" if @settings.has_key?(key)
raise "Setting key must be a Symbol" unless key.is_a? Symbol raise 'Setting key must be a Symbol' unless key.is_a? Symbol
@settings[key] = ConfigSetting.new(key, default, description) @settings[key] = ConfigSetting.new(key, default, description)
end end

View file

@ -1,39 +1,39 @@
# Rack Request # Rack Request
require "middleman-core/core_extensions/request" require 'middleman-core/core_extensions/request'
# File Change Notifier # File Change Notifier
require "middleman-core/core_extensions/file_watcher" require 'middleman-core/core_extensions/file_watcher'
# Custom Feature API # Custom Feature API
require "middleman-core/core_extensions/extensions" require 'middleman-core/core_extensions/extensions'
# Data looks at the data/ folder for YAML files and makes them available # Data looks at the data/ folder for YAML files and makes them available
# to dynamic requests. # to dynamic requests.
require "middleman-core/core_extensions/data" require 'middleman-core/core_extensions/data'
# Parse YAML from templates # Parse YAML from templates
require "middleman-core/core_extensions/front_matter" require 'middleman-core/core_extensions/front_matter'
# External helpers looks in the helpers/ folder for helper modules # External helpers looks in the helpers/ folder for helper modules
require "middleman-core/core_extensions/external_helpers" require 'middleman-core/core_extensions/external_helpers'
# Extended version of Padrino's rendering # Extended version of Padrino's rendering
require "middleman-core/core_extensions/rendering" require 'middleman-core/core_extensions/rendering'
# Pass custom options to views # Pass custom options to views
require "middleman-core/core_extensions/routing" require 'middleman-core/core_extensions/routing'
# Catch and show exceptions at the Rack level # Catch and show exceptions at the Rack level
require "middleman-core/core_extensions/show_exceptions" require 'middleman-core/core_extensions/show_exceptions'
# Setup default helpers # Setup default helpers
require "middleman-more/core_extensions/default_helpers" require 'middleman-more/core_extensions/default_helpers'
require "middleman-more/core_extensions/i18n" require 'middleman-more/core_extensions/i18n'
# Compass framework # Compass framework
begin begin
require "middleman-more/core_extensions/compass" require 'middleman-more/core_extensions/compass'
rescue LoadError rescue LoadError
$stderr.puts "Compass not installed: #{$!}" $stderr.puts "Compass not installed: #{$!}"
end end
@ -44,52 +44,52 @@ end
# CacheBuster adds a query string to assets in dynamic templates to # CacheBuster adds a query string to assets in dynamic templates to
# avoid browser caches failing to update to your new content. # avoid browser caches failing to update to your new content.
require "middleman-more/extensions/cache_buster" require 'middleman-more/extensions/cache_buster'
Middleman::Extensions::CacheBuster.register Middleman::Extensions::CacheBuster.register
# RelativeAssets allow any asset path in dynamic templates to be either # RelativeAssets allow any asset path in dynamic templates to be either
# relative to the root of the project or use an absolute URL. # relative to the root of the project or use an absolute URL.
require "middleman-more/extensions/relative_assets" require 'middleman-more/extensions/relative_assets'
Middleman::Extensions::RelativeAssets.register Middleman::Extensions::RelativeAssets.register
# AssetHost allows you to setup multiple domains to host your static # AssetHost allows you to setup multiple domains to host your static
# assets. Calls to asset paths in dynamic templates will then rotate # assets. Calls to asset paths in dynamic templates will then rotate
# through each of the asset servers to better spread the load. # through each of the asset servers to better spread the load.
require "middleman-more/extensions/asset_host" require 'middleman-more/extensions/asset_host'
Middleman::Extensions::AssetHost.register Middleman::Extensions::AssetHost.register
# MinifyCss compresses CSS # MinifyCss compresses CSS
require "middleman-more/extensions/minify_css" require 'middleman-more/extensions/minify_css'
Middleman::Extensions::MinifyCss.register Middleman::Extensions::MinifyCss.register
# MinifyJavascript compresses JS # MinifyJavascript compresses JS
require "middleman-more/extensions/minify_javascript" require 'middleman-more/extensions/minify_javascript'
Middleman::Extensions::MinifyJavascript.register Middleman::Extensions::MinifyJavascript.register
# GZIP assets and pages during build # GZIP assets and pages during build
require "middleman-more/extensions/gzip" require 'middleman-more/extensions/gzip'
Middleman::Extensions::Gzip.register Middleman::Extensions::Gzip.register
# AssetHash appends a hash of the file contents to the assets filename # AssetHash appends a hash of the file contents to the assets filename
# to avoid browser caches failing to update to your new content. # to avoid browser caches failing to update to your new content.
require "middleman-more/extensions/asset_hash" require 'middleman-more/extensions/asset_hash'
Middleman::Extensions::AssetHash.register Middleman::Extensions::AssetHash.register
# Provide Apache-style index.html files for directories # Provide Apache-style index.html files for directories
require "middleman-more/extensions/directory_indexes" require 'middleman-more/extensions/directory_indexes'
Middleman::Extensions::DirectoryIndexes.register Middleman::Extensions::DirectoryIndexes.register
# Lorem provides a handful of helpful prototyping methods to generate # Lorem provides a handful of helpful prototyping methods to generate
# words, paragraphs, fake images, names and email addresses. # words, paragraphs, fake images, names and email addresses.
require "middleman-more/extensions/lorem" require 'middleman-more/extensions/lorem'
# AutomaticImageSizes inspects the images used in your dynamic templates # AutomaticImageSizes inspects the images used in your dynamic templates
# and automatically adds width and height attributes to their HTML # and automatically adds width and height attributes to their HTML
# elements. # elements.
require "middleman-more/extensions/automatic_image_sizes" require 'middleman-more/extensions/automatic_image_sizes'
Middleman::Extensions::AutomaticImageSizes.register Middleman::Extensions::AutomaticImageSizes.register
# AutomaticAltTags uses the file name of the `image_tag` to generate # AutomaticAltTags uses the file name of the `image_tag` to generate
# a default `:alt` value. # a default `:alt` value.
require "middleman-more/extensions/automatic_alt_tags" require 'middleman-more/extensions/automatic_alt_tags'
Middleman::Extensions::AutomaticAltTags.register Middleman::Extensions::AutomaticAltTags.register

View file

@ -10,10 +10,10 @@ module Middleman
# @private # @private
def registered(app) def registered(app)
# Data formats # Data formats
require "yaml" require 'yaml'
require "active_support/json" require 'active_support/json'
app.config.define_setting :data_dir, "data", "The directory data files are stored in" app.config.define_setting :data_dir, 'data', 'The directory data files are stored in'
app.send :include, InstanceMethods app.send :include, InstanceMethods
end end
alias :included :registered alias :included :registered
@ -101,7 +101,7 @@ module Middleman
if %w(.yaml .yml).include?(extension) if %w(.yaml .yml).include?(extension)
data = YAML.load_file(full_path) data = YAML.load_file(full_path)
elsif extension == ".json" elsif extension == '.json'
data = ActiveSupport::JSON.decode(full_path.read) data = ActiveSupport::JSON.decode(full_path.read)
else else
return return

View file

@ -45,7 +45,7 @@ module Middleman
app.define_hook :development_config app.define_hook :development_config
app.config.define_setting :autoload_sprockets, true, 'Automatically load sprockets at startup?' app.config.define_setting :autoload_sprockets, true, 'Automatically load sprockets at startup?'
app.config[:autoload_sprockets] = (ENV["AUTOLOAD_SPROCKETS"] == "true") if ENV["AUTOLOAD_SPROCKETS"] app.config[:autoload_sprockets] = (ENV['AUTOLOAD_SPROCKETS'] == 'true') if ENV['AUTOLOAD_SPROCKETS']
app.extend ClassMethods app.extend ClassMethods
app.send :include, InstanceMethods app.send :include, InstanceMethods
@ -147,7 +147,7 @@ module Middleman
if config[:autoload_sprockets] if config[:autoload_sprockets]
begin begin
require "middleman-sprockets" require 'middleman-sprockets'
activate(:sprockets) activate(:sprockets)
rescue LoadError rescue LoadError
end end
@ -156,9 +156,9 @@ module Middleman
run_hook :before_configuration run_hook :before_configuration
# Check for and evaluate local configuration # Check for and evaluate local configuration
local_config = File.join(root, "config.rb") local_config = File.join(root, 'config.rb')
if File.exists? local_config if File.exists? local_config
logger.debug "== Reading: Local config" logger.debug '== Reading: Local config'
instance_eval File.read(local_config), local_config, 1 instance_eval File.read(local_config), local_config, 1
end end
@ -171,14 +171,14 @@ module Middleman
# don't completely reload middleman, I18n.load_path can get # don't completely reload middleman, I18n.load_path can get
# polluted with paths from other test app directories that don't # polluted with paths from other test app directories that don't
# exist anymore. # exist anymore.
if ENV["TEST"] if ENV['TEST']
::I18n.load_path.delete_if {|path| path =~ %r{tmp/aruba}} ::I18n.load_path.delete_if {|path| path =~ %r{tmp/aruba}}
::I18n.reload! ::I18n.reload!
end end
run_hook :after_configuration run_hook :after_configuration
logger.debug "Loaded extensions:" logger.debug 'Loaded extensions:'
self.extensions.each do |ext, klass| self.extensions.each do |ext, klass|
if ext.is_a?(Hash) if ext.is_a?(Hash)
ext.each do |k,_| ext.each do |k,_|

View file

@ -9,8 +9,8 @@ module Middleman
# once registered # once registered
def registered(app) def registered(app)
# Setup a default helpers paths # Setup a default helpers paths
app.config.define_setting :helpers_dir, "helpers", 'Directory to autoload helper modules from' app.config.define_setting :helpers_dir, 'helpers', 'Directory to autoload helper modules from'
app.config.define_setting :helpers_filename_glob, "**.rb", 'Glob pattern for matching helper ruby files' app.config.define_setting :helpers_filename_glob, '**.rb', 'Glob pattern for matching helper ruby files'
app.config.define_setting :helpers_filename_to_module_name_proc, Proc.new { |filename| app.config.define_setting :helpers_filename_to_module_name_proc, Proc.new { |filename|
basename = File.basename(filename, File.extname(filename)) basename = File.basename(filename, File.extname(filename))
basename.camelcase basename.camelcase

View file

@ -1,5 +1,5 @@
require "pathname" require 'pathname'
require "set" require 'set'
# API for watching file change events # API for watching file change events
module Middleman module Middleman
@ -128,7 +128,7 @@ module Middleman
path = Pathname(path) path = Pathname(path)
return unless path.exist? return unless path.exist?
glob = (path + "**").to_s glob = (path + '**').to_s
subset = @known_paths.select { |p| p.fnmatch(glob) } subset = @known_paths.select { |p| p.fnmatch(glob) }
::Middleman::Util.all_files_under(path).each do |filepath| ::Middleman::Util.all_files_under(path).each do |filepath|

View file

@ -1,11 +1,11 @@
require "active_support/core_ext/hash/keys" require 'active_support/core_ext/hash/keys'
require 'pathname' require 'pathname'
# Parsing YAML frontmatter # Parsing YAML frontmatter
require "yaml" require 'yaml'
# Parsing JSON frontmatter # Parsing JSON frontmatter
require "active_support/json" require 'active_support/json'
# Extensions namespace # Extensions namespace
module Middleman::CoreExtensions module Middleman::CoreExtensions
@ -108,9 +108,9 @@ module Middleman::CoreExtensions
# Copied from Sitemap::Store#file_to_path, but without # Copied from Sitemap::Store#file_to_path, but without
# removing the file extension # removing the file extension
file = File.join(app.root, file) file = File.join(app.root, file)
prefix = app.source_dir.sub(/\/$/, "") + "/" prefix = app.source_dir.sub(/\/$/, '') + '/'
return unless file.include?(prefix) return unless file.include?(prefix)
path = file.sub(prefix, "").sub(/\.frontmatter$/, "") path = file.sub(prefix, '').sub(/\.frontmatter$/, '')
@cache.delete(path) @cache.delete(path)
end end
@ -122,7 +122,7 @@ module Middleman::CoreExtensions
def parse_yaml_front_matter(content, full_path) def parse_yaml_front_matter(content, full_path)
yaml_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m yaml_regex = /\A(---\s*\n.*?\n?)^(---\s*$\n?)/m
if content =~ yaml_regex if content =~ yaml_regex
content = content.sub(yaml_regex, "") content = content.sub(yaml_regex, '')
begin begin
data = YAML.load($1) || {} data = YAML.load($1) || {}
@ -144,10 +144,10 @@ module Middleman::CoreExtensions
json_regex = /\A(;;;\s*\n.*?\n?)^(;;;\s*$\n?)/m json_regex = /\A(;;;\s*\n.*?\n?)^(;;;\s*$\n?)/m
if content =~ json_regex if content =~ json_regex
content = content.sub(json_regex, "") content = content.sub(json_regex, '')
begin begin
json = ($1+$2).sub(";;;", "{").sub(";;;", "}") json = ($1+$2).sub(';;;', '{').sub(';;;', '}')
data = ActiveSupport::JSON.decode(json).symbolize_keys data = ActiveSupport::JSON.decode(json).symbolize_keys
rescue => e rescue => e
app.logger.error "JSON Exception parsing #{full_path}: #{e.message}" app.logger.error "JSON Exception parsing #{full_path}: #{e.message}"
@ -196,7 +196,7 @@ module Middleman::CoreExtensions
end end
def normalize_path(path) def normalize_path(path)
path.sub(%r{^#{Regexp.escape(app.source_dir)}\/}, "") path.sub(%r{^#{Regexp.escape(app.source_dir)}\/}, '')
end end
end end
end end

View file

@ -28,65 +28,65 @@ module Middleman
require 'active_support/core_ext/string/output_safety' require 'active_support/core_ext/string/output_safety'
# Activate custom renderers # Activate custom renderers
require "middleman-core/renderers/erb" require 'middleman-core/renderers/erb'
app.register Middleman::Renderers::ERb app.register Middleman::Renderers::ERb
# CoffeeScript Support # CoffeeScript Support
begin begin
require "middleman-core/renderers/coffee_script" require 'middleman-core/renderers/coffee_script'
app.register Middleman::Renderers::CoffeeScript app.register Middleman::Renderers::CoffeeScript
rescue LoadError rescue LoadError
end end
# Haml Support # Haml Support
begin begin
require "middleman-core/renderers/haml" require 'middleman-core/renderers/haml'
app.register Middleman::Renderers::Haml app.register Middleman::Renderers::Haml
rescue LoadError rescue LoadError
end end
# Sass Support # Sass Support
begin begin
require "middleman-core/renderers/sass" require 'middleman-core/renderers/sass'
app.register Middleman::Renderers::Sass app.register Middleman::Renderers::Sass
rescue LoadError rescue LoadError
end end
# Markdown Support # Markdown Support
require "middleman-core/renderers/markdown" require 'middleman-core/renderers/markdown'
app.register Middleman::Renderers::Markdown app.register Middleman::Renderers::Markdown
# AsciiDoc Support # AsciiDoc Support
begin begin
require "middleman-core/renderers/asciidoc" require 'middleman-core/renderers/asciidoc'
app.register Middleman::Renderers::AsciiDoc app.register Middleman::Renderers::AsciiDoc
rescue LoadError rescue LoadError
end end
# Liquid Support # Liquid Support
begin begin
require "middleman-core/renderers/liquid" require 'middleman-core/renderers/liquid'
app.register Middleman::Renderers::Liquid app.register Middleman::Renderers::Liquid
rescue LoadError rescue LoadError
end end
# Slim Support # Slim Support
begin begin
require "middleman-core/renderers/slim" require 'middleman-core/renderers/slim'
app.register Middleman::Renderers::Slim app.register Middleman::Renderers::Slim
rescue LoadError rescue LoadError
end end
# Less Support # Less Support
begin begin
require "middleman-core/renderers/less" require 'middleman-core/renderers/less'
app.register Middleman::Renderers::Less app.register Middleman::Renderers::Less
rescue LoadError rescue LoadError
end end
# Stylus Support # Stylus Support
begin begin
require "middleman-core/renderers/stylus" require 'middleman-core/renderers/stylus'
app.register Middleman::Renderers::Stylus app.register Middleman::Renderers::Stylus
rescue LoadError rescue LoadError
end end
@ -198,7 +198,7 @@ module Middleman
engine = File.extname(resource.source_file)[1..-1].to_sym engine = File.extname(resource.source_file)[1..-1].to_sym
# Look for partials relative to the current path # Look for partials relative to the current path
relative_dir = File.join(current_dir.sub(%r{^#{Regexp.escape(self.source_dir)}/?}, ""), data) relative_dir = File.join(current_dir.sub(%r{^#{Regexp.escape(self.source_dir)}/?}, ''), data)
# Try to use the current engine first # Try to use the current engine first
found_partial, found_engine = resolve_template(relative_dir, :preferred_engine => engine, :try_without_underscore => true) found_partial, found_engine = resolve_template(relative_dir, :preferred_engine => engine, :try_without_underscore => true)
@ -246,7 +246,7 @@ module Middleman
context.current_engine, engine_was = engine, context.current_engine context.current_engine, engine_was = engine, context.current_engine
# Save current buffer for later # Save current buffer for later
@_out_buf, _buf_was = "", @_out_buf @_out_buf, _buf_was = '', @_out_buf
# Read from disk or cache the contents of the file # Read from disk or cache the contents of the file
body = if opts[:template_body] body = if opts[:template_body]
@ -284,7 +284,7 @@ module Middleman
content = callback.call(content, path, locs, template_class) content = callback.call(content, path, locs, template_class)
end end
output = ::ActiveSupport::SafeBuffer.new "" output = ::ActiveSupport::SafeBuffer.new ''
output.safe_concat content output.safe_concat content
output output
ensure ensure
@ -400,7 +400,7 @@ module Middleman
# @return [void] # @return [void]
def wrap_layout(layout_name, &block) def wrap_layout(layout_name, &block)
# Save current buffer for later # Save current buffer for later
@_out_buf, _buf_was = "", @_out_buf @_out_buf, _buf_was = '', @_out_buf
layout_path = locate_layout(layout_name, self.current_engine) layout_path = locate_layout(layout_name, self.current_engine)
@ -414,7 +414,7 @@ module Middleman
content = if block_given? content = if block_given?
capture_html(&block) capture_html(&block)
else else
"" ''
end end
ensure ensure
# Reset stored buffer # Reset stored buffer
@ -450,7 +450,7 @@ module Middleman
on_disk_path = File.expand_path(relative_path, self.source_dir) on_disk_path = File.expand_path(relative_path, self.source_dir)
# By default, any engine will do # By default, any engine will do
preferred_engine = "*" preferred_engine = '*'
# Unless we're specifically looking for a preferred engine # Unless we're specifically looking for a preferred engine
if options.has_key?(:preferred_engine) if options.has_key?(:preferred_engine)
@ -466,14 +466,14 @@ module Middleman
# Change the glob to only look for the matched extensions # Change the glob to only look for the matched extensions
if matched_exts.length > 0 if matched_exts.length > 0
preferred_engine = "{" + matched_exts.join(",") + "}" preferred_engine = '{' + matched_exts.join(',') + '}'
else else
return false return false
end end
end end
# Look for files that match # Look for files that match
path_with_ext = on_disk_path + "." + preferred_engine path_with_ext = on_disk_path + '.' + preferred_engine
found_path = Dir[path_with_ext].find do |path| found_path = Dir[path_with_ext].find do |path|
::Tilt[path] ::Tilt[path]
@ -481,8 +481,8 @@ module Middleman
if !found_path && options[:try_without_underscore] && if !found_path && options[:try_without_underscore] &&
path_no_underscore = path_with_ext. path_no_underscore = path_with_ext.
sub(relative_path, relative_path.sub(/^_/, ""). sub(relative_path, relative_path.sub(/^_/, '').
sub(/\/_/, "/")) sub(/\/_/, '/'))
found_path = Dir[path_no_underscore].find do |path| found_path = Dir[path_no_underscore].find do |path|
::Tilt[path] ::Tilt[path]
end end

View file

@ -1,8 +1,8 @@
# Built on Rack # Built on Rack
require "rack" require 'rack'
require "rack/file" require 'rack/file'
require "rack/lint" require 'rack/lint'
require "rack/head" require 'rack/head'
module Middleman module Middleman
module CoreExtensions module CoreExtensions
@ -77,7 +77,7 @@ module Middleman
end end
inner_app = inst(&block) inner_app = inst(&block)
app.map("/") { run inner_app } app.map('/') { run inner_app }
Array(@mappings).each do |path, block| Array(@mappings).each do |path, block|
app.map(path, &block) app.map(path, &block)
@ -227,7 +227,7 @@ module Middleman
start_time = Time.now start_time = Time.now
current_path = nil current_path = nil
request_path = URI.decode(env["PATH_INFO"].dup) request_path = URI.decode(env['PATH_INFO'].dup)
if request_path.respond_to? :force_encoding if request_path.respond_to? :force_encoding
request_path.force_encoding('UTF-8') request_path.force_encoding('UTF-8')
end end
@ -296,7 +296,7 @@ module Middleman
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise # Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500) # Rack will throw an error (500)
if !(100..199).include?(status) && ![204, 205, 304].include?(status) if !(100..199).include?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || "application/octet-stream" response[1]['Content-Type'] = resource.content_type || 'application/octet-stream'
end end
halt response halt response
end end

View file

@ -35,7 +35,7 @@ module Middleman
opts[:layout] = config[:layout] if opts[:layout].nil? opts[:layout] = config[:layout] if opts[:layout].nil?
# If the url is a regexp # If the url is a regexp
if url.is_a?(Regexp) || url.include?("*") if url.is_a?(Regexp) || url.include?('*')
# Use the metadata loop for matching against paths at runtime # Use the metadata loop for matching against paths at runtime
sitemap.provides_metadata_for_path(url) do |_| sitemap.provides_metadata_for_path(url) do |_|

View file

@ -1,5 +1,5 @@
require "active_support/core_ext/class/attribute" require 'active_support/core_ext/class/attribute'
require "active_support/core_ext/module/delegation" require 'active_support/core_ext/module/delegation'
module Middleman module Middleman
@ -53,7 +53,7 @@ module Middleman
end end
# Where to look in gems for extensions to auto-register # Where to look in gems for extensions to auto-register
EXTENSION_FILE = File.join("lib", "middleman_extension.rb") unless const_defined?(:EXTENSION_FILE) EXTENSION_FILE = File.join('lib', 'middleman_extension.rb') unless const_defined?(:EXTENSION_FILE)
class << self class << self
# Automatically load extensions from available RubyGems # Automatically load extensions from available RubyGems
@ -61,7 +61,7 @@ module Middleman
# #
# @private # @private
def load_extensions_in_path def load_extensions_in_path
require "rubygems" require 'rubygems'
extensions = rubygems_latest_specs.select do |spec| extensions = rubygems_latest_specs.select do |spec|
spec_has_file?(spec, EXTENSION_FILE) spec_has_file?(spec, EXTENSION_FILE)
@ -130,7 +130,7 @@ module Middleman
end end
def extension_name def extension_name
self.ext_name || self.name.underscore.split("/").last.to_sym self.ext_name || self.name.underscore.split('/').last.to_sym
end end
def register(n=self.extension_name) def register(n=self.extension_name)

View file

@ -1,5 +1,5 @@
# Core Pathname library used for traversal # Core Pathname library used for traversal
require "pathname" require 'pathname'
module Middleman module Middleman
@ -8,20 +8,20 @@ module Middleman
@_is_setup ||= begin @_is_setup ||= begin
# Only look for config.rb if MM_ROOT isn't set # Only look for config.rb if MM_ROOT isn't set
if !ENV["MM_ROOT"] && found_path = locate_root if !ENV['MM_ROOT'] && found_path = locate_root
ENV["MM_ROOT"] = found_path ENV['MM_ROOT'] = found_path
end end
is_bundler_setup = false is_bundler_setup = false
# If we've found the root, try to setup Bundler # If we've found the root, try to setup Bundler
if ENV["MM_ROOT"] if ENV['MM_ROOT']
root_gemfile = File.expand_path('Gemfile', ENV["MM_ROOT"]) root_gemfile = File.expand_path('Gemfile', ENV['MM_ROOT'])
ENV['BUNDLE_GEMFILE'] ||= root_gemfile ENV['BUNDLE_GEMFILE'] ||= root_gemfile
if !File.exists?(ENV['BUNDLE_GEMFILE']) if !File.exists?(ENV['BUNDLE_GEMFILE'])
git_gemfile = Pathname.new(__FILE__).expand_path.parent.parent.parent + "Gemfile" git_gemfile = Pathname.new(__FILE__).expand_path.parent.parent.parent + 'Gemfile'
ENV['BUNDLE_GEMFILE'] = git_gemfile.to_s ENV['BUNDLE_GEMFILE'] = git_gemfile.to_s
end end
@ -32,7 +32,7 @@ module Middleman
end end
# Automatically discover extensions in RubyGems # Automatically discover extensions in RubyGems
require "middleman-core/extensions" require 'middleman-core/extensions'
if is_bundler_setup if is_bundler_setup
Bundler.require Bundler.require

View file

@ -27,7 +27,7 @@ module Middleman
end end
def call(message, *args) def call(message, *args)
return if @instrumenting.is_a?(String) && @instrumenting != "instrument" && !message.include?(@instrumenting) return if @instrumenting.is_a?(String) && @instrumenting != 'instrument' && !message.include?(@instrumenting)
evt = ActiveSupport::Notifications::Event.new(message, *args) evt = ActiveSupport::Notifications::Event.new(message, *args)
self.info "== Instrument (#{evt.name.sub(/.middleman$/, '')}): #{evt.duration}ms" self.info "== Instrument (#{evt.name.sub(/.middleman$/, '')}): #{evt.duration}ms"

View file

@ -19,7 +19,7 @@ module Middleman
meta_pages = self meta_pages = self
@rack_app = Rack::Builder.new do @rack_app = Rack::Builder.new do
# Serve assets from metadata/assets # Serve assets from metadata/assets
use Rack::Static, :urls => ["/assets"], :root => File.join(File.dirname(__FILE__), 'meta_pages') use Rack::Static, :urls => ['/assets'], :root => File.join(File.dirname(__FILE__), 'meta_pages')
map '/' do map '/' do
run meta_pages.method(:index) run meta_pages.method(:index)
@ -96,7 +96,7 @@ module Middleman
# Respond to an HTML request # Respond to an HTML request
def response(content) def response(content)
[ 200, {"Content-Type" => "text/html"}, Array(content) ] [ 200, {'Content-Type' => 'text/html'}, Array(content) ]
end end
def extension_options(extension) def extension_options(extension)

View file

@ -10,18 +10,18 @@ module Middleman
end end
def render def render
content = "" content = ''
key_classes = ['key'] key_classes = ['key']
key_classes << 'modified' if @setting.value_set? key_classes << 'modified' if @setting.value_set?
content << content_tag(:span, @setting.key.inspect, :class => key_classes.join(' ')) content << content_tag(:span, @setting.key.inspect, :class => key_classes.join(' '))
content << " = " content << ' = '
content << content_tag(:span, @setting.value.inspect, :class => 'value') content << content_tag(:span, @setting.value.inspect, :class => 'value')
if @setting.default if @setting.default
content << content_tag(:span, :class => 'default') do content << content_tag(:span, :class => 'default') do
if @setting.value_set? if @setting.value_set?
"Default: #{@setting.default.inspect}" "Default: #{@setting.default.inspect}"
else else
"(Default)" '(Default)'
end end
end end
end end

View file

@ -17,10 +17,10 @@ module Middleman
def render def render
content_tag :div, :class => 'resource-details' do content_tag :div, :class => 'resource-details' do
content_tag :table do content_tag :table do
content = "" content = ''
resource_properties.each do |label, value| resource_properties.each do |label, value|
content << content_tag(:tr) do content << content_tag(:tr) do
row_content = "" row_content = ''
row_content << content_tag(:th, label) row_content << content_tag(:th, label)
row_content << content_tag(:td, value) row_content << content_tag(:td, value)
row_content.html_safe row_content.html_safe

View file

@ -13,7 +13,7 @@ module Middleman
end end
def render def render
content = "" content = ''
@children.keys.sort do |a,b| @children.keys.sort do |a,b|
a_subtree = @children[a] a_subtree = @children[a]
b_subtree = @children[b] b_subtree = @children[b]
@ -35,11 +35,11 @@ module Middleman
end.each do |path_part| end.each do |path_part|
subtree = @children[path_part] subtree = @children[path_part]
content << "<details class='#{subtree.css_classes.join(' ')}'>" content << "<details class='#{subtree.css_classes.join(' ')}'>"
content << "<summary>" content << '<summary>'
content << "<i class='icon-folder-open'></i>" unless subtree.is_a? SitemapResource content << "<i class='icon-folder-open'></i>" unless subtree.is_a? SitemapResource
content << "#{path_part}</summary>" content << "#{path_part}</summary>"
content << subtree.render content << subtree.render
content << "</details>" content << '</details>'
end end
content content
end end
@ -66,7 +66,7 @@ module Middleman
end end
def to_s def to_s
"Sitemap Tree" 'Sitemap Tree'
end end
end end
end end

View file

@ -1,4 +1,4 @@
require "webrick" require 'webrick'
require 'middleman-core/meta_pages' require 'middleman-core/meta_pages'
module Middleman module Middleman
@ -29,7 +29,7 @@ module Middleman
# Save the last-used @options so it may be re-used when # Save the last-used @options so it may be re-used when
# reloading later on. # reloading later on.
::Middleman::Profiling.report("server_start") ::Middleman::Profiling.report('server_start')
loop do loop do
@webrick.start @webrick.start
@ -50,7 +50,7 @@ module Middleman
# @return [void] # @return [void]
def stop def stop
begin begin
logger.info "== The Middleman is shutting down" logger.info '== The Middleman is shutting down'
rescue rescue
# if the user closed their terminal STDOUT/STDERR won't exist # if the user closed their terminal STDOUT/STDERR won't exist
end end
@ -65,20 +65,20 @@ module Middleman
# Simply stop, then start the server # Simply stop, then start the server
# @return [void] # @return [void]
def reload def reload
logger.info "== The Middleman is reloading" logger.info '== The Middleman is reloading'
begin begin
app = new_app app = new_app
rescue Exception => e rescue Exception => e
logger.error "Error reloading Middleman: #{e}\n#{e.backtrace.join("\n")}" logger.error "Error reloading Middleman: #{e}\n#{e.backtrace.join("\n")}"
logger.info "== The Middleman is still running the application from before the error" logger.info '== The Middleman is still running the application from before the error'
return return
end end
unmount_instance unmount_instance
mount_instance(app) mount_instance(app)
logger.info "== The Middleman has reloaded" logger.info '== The Middleman has reloaded'
end end
# Stop the current instance, exit Webrick # Stop the current instance, exit Webrick
@ -115,7 +115,7 @@ module Middleman
if first_run if first_run
# Watcher Library # Watcher Library
require "listen" require 'listen'
@listener = Listen.to(Dir.pwd, :relative_paths => true, :force_polling => @options[:force_polling]) @listener = Listen.to(Dir.pwd, :relative_paths => true, :force_polling => @options[:force_polling])
@listener.latency(@options[:latency]) @listener.latency(@options[:latency])
end end
@ -190,13 +190,13 @@ module Middleman
start_file_watcher start_file_watcher
rack_app = app.class.to_rack_app rack_app = app.class.to_rack_app
@webrick.mount "/", ::Rack::Handler::WEBrick, rack_app @webrick.mount '/', ::Rack::Handler::WEBrick, rack_app
end end
# Detach the current Middleman::Application instance # Detach the current Middleman::Application instance
# @return [void] # @return [void]
def unmount_instance def unmount_instance
@webrick.unmount "/" @webrick.unmount '/'
@app = nil @app = nil
end end

View file

@ -46,7 +46,7 @@ module Middleman
result = RubyProf.stop result = RubyProf.stop
printer = RubyProf::GraphHtmlPrinter.new(result) printer = RubyProf::GraphHtmlPrinter.new(result)
outfile = File.join("profile", report_name) outfile = File.join('profile', report_name)
outfile = (outfile + '.html') unless outfile.end_with? '.html' outfile = (outfile + '.html') unless outfile.end_with? '.html'
FileUtils.mkdir_p(File.dirname(outfile)) FileUtils.mkdir_p(File.dirname(outfile))
File.open(outfile, 'w') do |f| File.open(outfile, 'w') do |f|

View file

@ -1,5 +1,5 @@
# Require gem # Require gem
require "coffee_script" require 'coffee_script'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -21,7 +21,7 @@ module Middleman
# Convert symbols to classes # Convert symbols to classes
if config[:erb_engine].is_a? Symbol if config[:erb_engine].is_a? Symbol
engine = engine.to_s engine = engine.to_s
engine = engine == "erb" ? "ERB" : engine.camelize engine = engine == 'erb' ? 'ERB' : engine.camelize
config[:erb_engine] = config[:erb_engine_prefix].const_get("#{engine}Template") config[:erb_engine] = config[:erb_engine_prefix].const_get("#{engine}Template")
end end

View file

@ -1,5 +1,5 @@
# Require gem # Require gem
require "haml" require 'haml'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -1,4 +1,4 @@
require "kramdown" require 'kramdown'
module Middleman module Middleman
module Renderers module Renderers
@ -30,7 +30,7 @@ module Middleman
if el.attr['href'] =~ /\Amailto:/ if el.attr['href'] =~ /\Amailto:/
mail_addr = el.attr['href'].sub(/\Amailto:/, '') mail_addr = el.attr['href'].sub(/\Amailto:/, '')
href = obfuscate('mailto') << ":" << obfuscate(mail_addr) href = obfuscate('mailto') << ':' << obfuscate(mail_addr)
content = obfuscate(content) if content == mail_addr content = obfuscate(content) if content == mail_addr
return %Q{<a href="#{href}">#{content}</a>} return %Q{<a href="#{href}">#{content}</a>}
end end

View file

@ -1,4 +1,4 @@
require "less" require 'less'
module Middleman module Middleman
module Renderers module Renderers
@ -37,7 +37,7 @@ module Middleman
if ::Less.const_defined? :Engine if ::Less.const_defined? :Engine
@engine = ::Less::Engine.new(data) @engine = ::Less::Engine.new(data)
else else
parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line, :paths => [".", File.dirname(eval_file)]) parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line, :paths => ['.', File.dirname(eval_file)])
@engine = parser.parse(data) @engine = parser.parse(data)
end end
end end

View file

@ -1,5 +1,5 @@
# Require Gem # Require Gem
require "liquid" require 'liquid'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -28,18 +28,18 @@ module Middleman
begin begin
# Look for the user's preferred engine # Look for the user's preferred engine
if config[:markdown_engine] == :redcarpet if config[:markdown_engine] == :redcarpet
require "middleman-core/renderers/redcarpet" require 'middleman-core/renderers/redcarpet'
::Tilt.prefer(::Middleman::Renderers::RedcarpetTemplate, *markdown_exts) ::Tilt.prefer(::Middleman::Renderers::RedcarpetTemplate, *markdown_exts)
MiddlemanRedcarpetHTML.middleman_app = self MiddlemanRedcarpetHTML.middleman_app = self
elsif config[:markdown_engine] == :kramdown elsif config[:markdown_engine] == :kramdown
require "middleman-core/renderers/kramdown" require 'middleman-core/renderers/kramdown'
::Tilt.prefer(::Middleman::Renderers::KramdownTemplate, *markdown_exts) ::Tilt.prefer(::Middleman::Renderers::KramdownTemplate, *markdown_exts)
MiddlemanKramdownHTML.middleman_app = self MiddlemanKramdownHTML.middleman_app = self
elsif !config[:markdown_engine].nil? elsif !config[:markdown_engine].nil?
# Map symbols to classes # Map symbols to classes
markdown_engine_klass = if config[:markdown_engine].is_a? Symbol markdown_engine_klass = if config[:markdown_engine].is_a? Symbol
engine = config[:markdown_engine].to_s engine = config[:markdown_engine].to_s
engine = engine == "rdiscount" ? "RDiscount" : engine.camelize engine = engine == 'rdiscount' ? 'RDiscount' : engine.camelize
config[:markdown_engine_prefix].const_get("#{engine}Template") config[:markdown_engine_prefix].const_get("#{engine}Template")
else else
config[:markdown_engine_prefix] config[:markdown_engine_prefix]

View file

@ -1,4 +1,4 @@
require "redcarpet" require 'redcarpet'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -1,4 +1,4 @@
require "sass" require 'sass'
module Middleman module Middleman
module Renderers module Renderers
@ -79,7 +79,7 @@ module Middleman
parts = basename.split('.') parts = basename.split('.')
parts.pop parts.pop
more_opts[:css_filename] = File.join(location_of_sass_file, @context.config[:css_dir], parts.join(".")) more_opts[:css_filename] = File.join(location_of_sass_file, @context.config[:css_dir], parts.join('.'))
end end
options.merge(more_opts) options.merge(more_opts)

View file

@ -1,5 +1,5 @@
# Load gem # Load gem
require "slim" require 'slim'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -1,5 +1,5 @@
require "stylus" require 'stylus'
require "stylus/tilt" require 'stylus/tilt'
module Middleman module Middleman
module Renderers module Renderers

View file

@ -1,11 +1,11 @@
require "middleman-core/sitemap/store" require 'middleman-core/sitemap/store'
require "middleman-core/sitemap/resource" require 'middleman-core/sitemap/resource'
require "middleman-core/sitemap/extensions/on_disk" require 'middleman-core/sitemap/extensions/on_disk'
require "middleman-core/sitemap/extensions/redirects" require 'middleman-core/sitemap/extensions/redirects'
require "middleman-core/sitemap/extensions/request_endpoints" require 'middleman-core/sitemap/extensions/request_endpoints'
require "middleman-core/sitemap/extensions/proxies" require 'middleman-core/sitemap/extensions/proxies'
require "middleman-core/sitemap/extensions/ignores" require 'middleman-core/sitemap/extensions/ignores'
# Core Sitemap Extensions # Core Sitemap Extensions
module Middleman module Middleman

View file

@ -28,7 +28,7 @@ module Middleman
def ignored? def ignored?
@app.ignore_manager.ignored?(path) || @app.ignore_manager.ignored?(path) ||
(!proxy? && (!proxy? &&
@app.ignore_manager.ignored?(source_file.sub("#{@app.source_dir}/", "")) @app.ignore_manager.ignored?(source_file.sub("#{@app.source_dir}/", ''))
) )
end end
end end
@ -64,7 +64,7 @@ module Middleman
@ignored_callbacks << Proc.new {|p| p =~ path } @ignored_callbacks << Proc.new {|p| p =~ path }
elsif path.is_a? String elsif path.is_a? String
path_clean = ::Middleman::Util.normalize_path(path) path_clean = ::Middleman::Util.normalize_path(path)
if path_clean.include?("*") # It's a glob if path_clean.include?('*') # It's a glob
@ignored_callbacks << Proc.new {|p| File.fnmatch(path_clean, p) } @ignored_callbacks << Proc.new {|p| File.fnmatch(path_clean, p) }
else else
# Add a specific-path ignore unless that path is already covered # Add a specific-path ignore unless that path is already covered

View file

@ -8,7 +8,7 @@ module Middleman
# This resource's parent resource # This resource's parent resource
# @return [Middleman::Sitemap::Resource, nil] # @return [Middleman::Sitemap::Resource, nil]
def parent def parent
parts = path.split("/") parts = path.split('/')
parts.pop if path.include?(app.index_file) parts.pop if path.include?(app.index_file)
return nil if parts.length < 1 return nil if parts.length < 1
@ -16,7 +16,7 @@ module Middleman
parts.pop parts.pop
parts << app.index_file parts << app.index_file
parent_path = "/" + parts.join("/") parent_path = '/' + parts.join('/')
store.find_resource_by_destination_path(parent_path) store.find_resource_by_destination_path(parent_path)
end end
@ -30,7 +30,7 @@ module Middleman
base_path = eponymous_directory_path base_path = eponymous_directory_path
prefix = %r|^#{base_path.sub("/", "\\/")}| prefix = %r|^#{base_path.sub("/", "\\/")}|
else else
base_path = path.sub("#{app.index_file}", "") base_path = path.sub("#{app.index_file}", '')
prefix = %r|^#{base_path.sub("/", "\\/")}| prefix = %r|^#{base_path.sub("/", "\\/")}|
end end
@ -38,8 +38,8 @@ module Middleman
if sub_resource.path == self.path || sub_resource.path !~ prefix if sub_resource.path == self.path || sub_resource.path !~ prefix
false false
else else
inner_path = sub_resource.path.sub(prefix, "") inner_path = sub_resource.path.sub(prefix, '')
parts = inner_path.split("/") parts = inner_path.split('/')
if parts.length == 1 if parts.length == 1
true true
elsif parts.length == 2 elsif parts.length == 2
@ -79,7 +79,7 @@ module Middleman
# (e.g., for 'gallery.html' this would return 'gallery/') # (e.g., for 'gallery.html' this would return 'gallery/')
# @return [String] # @return [String]
def eponymous_directory_path def eponymous_directory_path
path.sub(ext, '/').sub(/\/$/, "") + "/" path.sub(ext, '/').sub(/\/$/, '') + '/'
end end
end end
end end

View file

@ -1,4 +1,4 @@
require "active_support/core_ext/object/inclusion" require 'active_support/core_ext/object/inclusion'
module Middleman module Middleman
module Sitemap module Sitemap

View file

@ -1,5 +1,5 @@
require "middleman-core/sitemap/extensions/traversal" require 'middleman-core/sitemap/extensions/traversal'
require "middleman-core/sitemap/extensions/content_type" require 'middleman-core/sitemap/extensions/content_type'
module Middleman module Middleman
@ -111,14 +111,14 @@ module Middleman
relative_source = Pathname(source_file).relative_path_from(Pathname(app.root)) relative_source = Pathname(source_file).relative_path_from(Pathname(app.root))
instrument "render.resource", :path => relative_source do instrument 'render.resource', :path => relative_source do
md = metadata.dup md = metadata.dup
opts = md[:options].deep_merge(opts) opts = md[:options].deep_merge(opts)
# Pass "renderer_options" hash from frontmatter along to renderer # Pass "renderer_options" hash from frontmatter along to renderer
if md[:page]["renderer_options"] if md[:page]['renderer_options']
opts[:renderer_options] = {} opts[:renderer_options] = {}
md[:page]["renderer_options"].each do |k, v| md[:page]['renderer_options'].each do |k, v|
opts[:renderer_options][k.to_sym] = v opts[:renderer_options][k.to_sym] = v
end end
end end
@ -127,7 +127,7 @@ module Middleman
# Forward remaining data to helpers # Forward remaining data to helpers
if md.has_key?(:page) if md.has_key?(:page)
app.data.store("page", md[:page]) app.data.store('page', md[:page])
end end
blocks = Array(md[:blocks]).dup blocks = Array(md[:blocks]).dup

View file

@ -1,7 +1,7 @@
# Used for merging results of metadata callbacks # Used for merging results of metadata callbacks
require "active_support/core_ext/hash/deep_merge" require 'active_support/core_ext/hash/deep_merge'
require 'monitor' require 'monitor'
require "middleman-core/sitemap/queryable" require 'middleman-core/sitemap/queryable'
module Middleman module Middleman
@ -161,7 +161,7 @@ module Middleman
when Regexp when Regexp
next result unless request_path =~ matcher next result unless request_path =~ matcher
when String when String
next result unless File.fnmatch("/" + Util.strip_leading_slash(matcher), "/#{request_path}") next result unless File.fnmatch('/' + Util.strip_leading_slash(matcher), "/#{request_path}")
end end
metadata = callback.call(request_path).dup metadata = callback.call(request_path).dup
@ -178,14 +178,14 @@ module Middleman
def file_to_path(file) def file_to_path(file)
file = File.join(@app.root, file) file = File.join(@app.root, file)
prefix = @app.source_dir.sub(/\/$/, "") + "/" prefix = @app.source_dir.sub(/\/$/, '') + '/'
return false unless file.start_with?(prefix) return false unless file.start_with?(prefix)
path = file.sub(prefix, "") path = file.sub(prefix, '')
# Replace a file name containing automatic_directory_matcher with a folder # Replace a file name containing automatic_directory_matcher with a folder
unless @app.config[:automatic_directory_matcher].nil? unless @app.config[:automatic_directory_matcher].nil?
path = path.gsub(@app.config[:automatic_directory_matcher], "/") path = path.gsub(@app.config[:automatic_directory_matcher], '/')
end end
extensionless_path(path) extensionless_path(path)
@ -211,7 +211,7 @@ module Middleman
return unless @needs_sitemap_rebuild return unless @needs_sitemap_rebuild
@needs_sitemap_rebuild = false @needs_sitemap_rebuild = false
@app.logger.debug "== Rebuilding resource list" @app.logger.debug '== Rebuilding resource list'
@resources = @resource_list_manipulators.inject([]) do |result, (_, inst)| @resources = @resource_list_manipulators.inject([]) do |result, (_, inst)|
newres = inst.manipulate_resource_list(result) newres = inst.manipulate_resource_list(result)
@ -244,7 +244,7 @@ module Middleman
# @return [String] # @return [String]
def remove_templating_extensions(path) def remove_templating_extensions(path)
# Strip templating extensions as long as Tilt knows them # Strip templating extensions as long as Tilt knows them
path = path.sub(File.extname(path), "") while ::Tilt[path] path = path.sub(File.extname(path), '') while ::Tilt[path]
path path
end end
@ -270,7 +270,7 @@ module Middleman
input_ext = File.extname(file) input_ext = File.extname(file)
if !input_ext.empty? if !input_ext.empty?
input_ext = input_ext.split(".").last.to_sym input_ext = input_ext.split('.').last.to_sym
if @app.template_extensions.has_key?(input_ext) if @app.template_extensions.has_key?(input_ext)
path << ".#{@app.template_extensions[input_ext]}" path << ".#{@app.template_extensions[input_ext]}"
end end

View file

@ -1,11 +1,11 @@
MIDDLEMAN_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__))) MIDDLEMAN_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__)))
MIDDLEMAN_BIN_PATH = File.join(MIDDLEMAN_ROOT_PATH, "bin") MIDDLEMAN_BIN_PATH = File.join(MIDDLEMAN_ROOT_PATH, 'bin')
ENV['PATH'] = "#{MIDDLEMAN_BIN_PATH}#{File::PATH_SEPARATOR}#{ENV['PATH']}" ENV['PATH'] = "#{MIDDLEMAN_BIN_PATH}#{File::PATH_SEPARATOR}#{ENV['PATH']}"
require "aruba/cucumber" require 'aruba/cucumber'
require "middleman-core/step_definitions/middleman_steps" require 'middleman-core/step_definitions/middleman_steps'
require "middleman-core/step_definitions/builder_steps" require 'middleman-core/step_definitions/builder_steps'
require "middleman-core/step_definitions/server_steps" require 'middleman-core/step_definitions/server_steps'
Before do Before do
@aruba_timeout_seconds = 30 @aruba_timeout_seconds = 30

View file

@ -5,20 +5,20 @@ Before do
end end
Given /^app "([^\"]*)" is using config "([^\"]*)"$/ do |path, config_name| Given /^app "([^\"]*)" is using config "([^\"]*)"$/ do |path, config_name|
target = File.join(PROJECT_ROOT_PATH, "fixtures", path) target = File.join(PROJECT_ROOT_PATH, 'fixtures', path)
config_path = File.join(current_dir, "config-#{config_name}.rb") config_path = File.join(current_dir, "config-#{config_name}.rb")
config_dest = File.join(current_dir, "config.rb") config_dest = File.join(current_dir, 'config.rb')
FileUtils.cp(config_path, config_dest) FileUtils.cp(config_path, config_dest)
end end
Given /^an empty app$/ do Given /^an empty app$/ do
step %Q{a directory named "empty_app"} step %Q{a directory named "empty_app"}
step %Q{I cd to "empty_app"} step %Q{I cd to "empty_app"}
ENV["MM_ROOT"] = nil ENV['MM_ROOT'] = nil
end end
Given /^a fixture app "([^\"]*)"$/ do |path| Given /^a fixture app "([^\"]*)"$/ do |path|
ENV["MM_ROOT"] = nil ENV['MM_ROOT'] = nil
# This step can be reentered from several places but we don't want # This step can be reentered from several places but we don't want
# to keep re-copying and re-cd-ing into ever-deeper directories # to keep re-copying and re-cd-ing into ever-deeper directories
@ -26,7 +26,7 @@ Given /^a fixture app "([^\"]*)"$/ do |path|
step %Q{a directory named "#{path}"} step %Q{a directory named "#{path}"}
target_path = File.join(PROJECT_ROOT_PATH, "fixtures", path) target_path = File.join(PROJECT_ROOT_PATH, 'fixtures', path)
FileUtils.cp_r(target_path, current_dir) FileUtils.cp_r(target_path, current_dir)
step %Q{I cd to "#{path}"} step %Q{I cd to "#{path}"}

View file

@ -1,6 +1,6 @@
# encoding: UTF-8 # encoding: UTF-8
require "rack/test" require 'rack/test'
Given /^a clean server$/ do Given /^a clean server$/ do
@initialize_commands = [] @initialize_commands = []
@ -9,7 +9,7 @@ end
Given /^"([^\"]*)" feature is "([^\"]*)"$/ do |feature, state| Given /^"([^\"]*)" feature is "([^\"]*)"$/ do |feature, state|
@initialize_commands ||= [] @initialize_commands ||= []
if state == "enabled" if state == 'enabled'
@initialize_commands << lambda { activate(feature.to_sym) } @initialize_commands << lambda { activate(feature.to_sym) }
end end
end end
@ -34,13 +34,13 @@ end
Given /^the Server is running$/ do Given /^the Server is running$/ do
root_dir = File.expand_path(current_dir) root_dir = File.expand_path(current_dir)
if File.exists?(File.join(root_dir, "source")) if File.exists?(File.join(root_dir, 'source'))
ENV["MM_SOURCE"] = "source" ENV['MM_SOURCE'] = 'source'
else else
ENV["MM_SOURCE"] = "" ENV['MM_SOURCE'] = ''
end end
ENV["MM_ROOT"] = root_dir ENV['MM_ROOT'] = root_dir
initialize_commands = @initialize_commands || [] initialize_commands = @initialize_commands || []
initialize_commands.unshift lambda { initialize_commands.unshift lambda {

View file

@ -1,6 +1,6 @@
# Use thor for template generation # Use thor for template generation
require "thor" require 'thor'
require "thor/group" require 'thor/group'
# Templates namespace # Templates namespace
module Middleman::Templates module Middleman::Templates
@ -37,14 +37,14 @@ module Middleman::Templates
# The gemfile template to use. Individual templates can define this class # The gemfile template to use. Individual templates can define this class
# method to override the template path. # method to override the template path.
def self.gemfile_template def self.gemfile_template
"shared/Gemfile.tt" 'shared/Gemfile.tt'
end end
# Required path for the new project to be generated # Required path for the new project to be generated
argument :location, :type => :string argument :location, :type => :string
# Name of the template being used to generate the project. # Name of the template being used to generate the project.
class_option :template, :default => "default" class_option :template, :default => 'default'
# Output a config.ru file for Rack if --rack is passed # Output a config.ru file for Rack if --rack is passed
class_option :rack, :type => :boolean, :default => false class_option :rack, :type => :boolean, :default => false
@ -53,7 +53,7 @@ module Middleman::Templates
# @return [void] # @return [void]
def generate_rack! def generate_rack!
return unless options[:rack] return unless options[:rack]
template "shared/config.ru", File.join(location, "config.ru") template 'shared/config.ru', File.join(location, 'config.ru')
end end
class_option :'skip-bundle', :type => :boolean, :default => false class_option :'skip-bundle', :type => :boolean, :default => false
@ -63,12 +63,12 @@ module Middleman::Templates
# @return [void] # @return [void]
def generate_bundler! def generate_bundler!
return if options[:'skip-gemfile'] return if options[:'skip-gemfile']
template self.class.gemfile_template, File.join(location, "Gemfile") template self.class.gemfile_template, File.join(location, 'Gemfile')
return if options[:'skip-bundle'] return if options[:'skip-bundle']
inside(location) do inside(location) do
::Middleman::Cli::Bundle.new.invoke(:bundle) ::Middleman::Cli::Bundle.new.invoke(:bundle)
end unless ENV["TEST"] end unless ENV['TEST']
end end
# Output a .gitignore file # Output a .gitignore file
@ -78,25 +78,25 @@ module Middleman::Templates
# @return [void] # @return [void]
def generate_gitignore! def generate_gitignore!
return if options[:'skip-git'] return if options[:'skip-git']
copy_file "shared/gitignore", File.join(location, ".gitignore") copy_file 'shared/gitignore', File.join(location, '.gitignore')
end end
end end
end end
# Default template # Default template
require "middleman-core/templates/default" require 'middleman-core/templates/default'
# HTML5 template # HTML5 template
require "middleman-core/templates/html5" require 'middleman-core/templates/html5'
# HTML5 Mobile template # HTML5 Mobile template
require "middleman-core/templates/mobile" require 'middleman-core/templates/mobile'
# SMACSS templates # SMACSS templates
require "middleman-more/templates/smacss" require 'middleman-more/templates/smacss'
# Local templates # Local templates
require "middleman-core/templates/local" require 'middleman-core/templates/local'
# Barebones template # Barebones template
require "middleman-core/templates/empty" require 'middleman-core/templates/empty'

View file

@ -1,14 +1,14 @@
# Default Middleman template # Default Middleman template
class Middleman::Templates::Default < Middleman::Templates::Base class Middleman::Templates::Default < Middleman::Templates::Base
class_option "css_dir", class_option 'css_dir',
:default => "stylesheets", :default => 'stylesheets',
:desc => 'The path to the css files' :desc => 'The path to the css files'
class_option "js_dir", class_option 'js_dir',
:default => "javascripts", :default => 'javascripts',
:desc => 'The path to the javascript files' :desc => 'The path to the javascript files'
class_option "images_dir", class_option 'images_dir',
:default => "images", :default => 'images',
:desc => 'The path to the image files' :desc => 'The path to the image files'
# Template files are relative to this file # Template files are relative to this file
@ -20,17 +20,17 @@ class Middleman::Templates::Default < Middleman::Templates::Base
# Actually output the files # Actually output the files
# @return [void] # @return [void]
def build_scaffold! def build_scaffold!
template "shared/config.tt", File.join(location, "config.rb") template 'shared/config.tt', File.join(location, 'config.rb')
copy_file "default/source/index.html.erb", File.join(location, "source/index.html.erb") copy_file 'default/source/index.html.erb', File.join(location, 'source/index.html.erb')
copy_file "default/source/layouts/layout.erb", File.join(location, "source/layouts/layout.erb") copy_file 'default/source/layouts/layout.erb', File.join(location, 'source/layouts/layout.erb')
empty_directory File.join(location, "source", options[:css_dir]) empty_directory File.join(location, 'source', options[:css_dir])
copy_file "default/source/stylesheets/all.css", File.join(location, "source", options[:css_dir], "all.css") copy_file 'default/source/stylesheets/all.css', File.join(location, 'source', options[:css_dir], 'all.css')
copy_file "default/source/stylesheets/normalize.css", File.join(location, "source", options[:css_dir], "normalize.css") copy_file 'default/source/stylesheets/normalize.css', File.join(location, 'source', options[:css_dir], 'normalize.css')
empty_directory File.join(location, "source", options[:js_dir]) empty_directory File.join(location, 'source', options[:js_dir])
copy_file "default/source/javascripts/all.js", File.join(location, "source", options[:js_dir], "all.js") copy_file 'default/source/javascripts/all.js', File.join(location, 'source', options[:js_dir], 'all.js')
empty_directory File.join(location, "source", options[:images_dir]) empty_directory File.join(location, 'source', options[:images_dir])
copy_file "default/source/images/background.png", File.join(location, "source", options[:images_dir], "background.png") copy_file 'default/source/images/background.png', File.join(location, 'source', options[:images_dir], 'background.png')
copy_file "default/source/images/middleman.png", File.join(location, "source", options[:images_dir], "middleman.png") copy_file 'default/source/images/middleman.png', File.join(location, 'source', options[:images_dir], 'middleman.png')
end end
end end

View file

@ -8,14 +8,14 @@ class Middleman::Templates::Empty < Middleman::Templates::Base
end end
def self.gemfile_template def self.gemfile_template
"empty/Gemfile.tt" 'empty/Gemfile.tt'
end end
# Actually output the files # Actually output the files
# @return [void] # @return [void]
def build_scaffold! def build_scaffold!
create_file File.join(location, "config.rb"), "\n" create_file File.join(location, 'config.rb'), "\n"
empty_directory File.join(location, "source") empty_directory File.join(location, 'source')
end end
end end

View file

@ -9,6 +9,6 @@ end
require 'rake/clean' require 'rake/clean'
task :test => ["cucumber"] task :test => ['cucumber']
task :default => :test task :default => :test

View file

@ -1,4 +1,4 @@
PROJECT_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__))) PROJECT_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__)))
require "middleman-core" require 'middleman-core'
require "middleman-core/step_definitions" require 'middleman-core/step_definitions'
require File.join(PROJECT_ROOT_PATH, 'lib', '<%= name %>') require File.join(PROJECT_ROOT_PATH, 'lib', '<%= name %>')

View file

@ -1,9 +1,9 @@
# Require core library # Require core library
require "middleman-core" require 'middleman-core'
# Extension namespace # Extension namespace
class MyExtension < ::Middleman::Extension class MyExtension < ::Middleman::Extension
option :my_option, "default", "An example option" option :my_option, 'default', 'An example option'
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
# Call super to build options from the options_hash # Call super to build options from the options_hash

View file

@ -1 +1 @@
require "<%= name %>" require '<%= name %>'

View file

@ -1,14 +1,14 @@
# HTML5 Boilerplate template # HTML5 Boilerplate template
class Middleman::Templates::Html5 < Middleman::Templates::Base class Middleman::Templates::Html5 < Middleman::Templates::Base
class_option "css_dir", class_option 'css_dir',
:default => "css", :default => 'css',
:desc => 'The path to the css files' :desc => 'The path to the css files'
class_option "js_dir", class_option 'js_dir',
:default => "js", :default => 'js',
:desc => 'The path to the javascript files' :desc => 'The path to the javascript files'
class_option "images_dir", class_option 'images_dir',
:default => "img", :default => 'img',
:desc => 'The path to the image files' :desc => 'The path to the image files'
# Templates are relative to this file # Templates are relative to this file
@ -20,9 +20,9 @@ class Middleman::Templates::Html5 < Middleman::Templates::Base
# Output the files # Output the files
# @return [void] # @return [void]
def build_scaffold! def build_scaffold!
template "shared/config.tt", File.join(location, "config.rb") template 'shared/config.tt', File.join(location, 'config.rb')
directory "html5/source", File.join(location, "source") directory 'html5/source', File.join(location, 'source')
empty_directory File.join(location, "source") empty_directory File.join(location, 'source')
end end
end end

View file

@ -4,7 +4,7 @@ class Middleman::Templates::Local < Middleman::Templates::Base
# Look for templates in ~/.middleman # Look for templates in ~/.middleman
# @return [String] # @return [String]
def self.source_root def self.source_root
File.join(File.expand_path("~/"), ".middleman") File.join(File.expand_path('~/'), '.middleman')
end end
# Just copy from the template path # Just copy from the template path
@ -15,10 +15,10 @@ class Middleman::Templates::Local < Middleman::Templates::Base
end end
# Iterate over the directories in the templates path and register each one. # Iterate over the directories in the templates path and register each one.
Dir[File.join(Middleman::Templates::Local.source_root, "*")].each do |dir| Dir[File.join(Middleman::Templates::Local.source_root, '*')].each do |dir|
next unless File.directory?(dir) next unless File.directory?(dir)
template_file = File.join(dir, "template.rb") template_file = File.join(dir, 'template.rb')
if File.exists?(template_file) if File.exists?(template_file)
require template_file require template_file

View file

@ -2,9 +2,9 @@
class Middleman::Templates::Mobile < Middleman::Templates::Base class Middleman::Templates::Mobile < Middleman::Templates::Base
# Slightly different paths # Slightly different paths
class_option :css_dir, :default => "css" class_option :css_dir, :default => 'css'
class_option :js_dir, :default => "js" class_option :js_dir, :default => 'js'
class_option :images_dir, :default => "img" class_option :images_dir, :default => 'img'
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]
@ -15,9 +15,9 @@ class Middleman::Templates::Mobile < Middleman::Templates::Base
# Output the files # Output the files
# @return [void] # @return [void]
def build_scaffold! def build_scaffold!
template "shared/config.tt", File.join(location, "config.rb") template 'shared/config.tt', File.join(location, 'config.rb')
directory "mobile/source", File.join(location, "source") directory 'mobile/source', File.join(location, 'source')
empty_directory File.join(location, "source") empty_directory File.join(location, 'source')
end end
end end

View file

@ -1,17 +1,17 @@
# Our custom logger # Our custom logger
require "middleman-core/logger" require 'middleman-core/logger'
# For instrumenting # For instrumenting
require "active_support/notifications" require 'active_support/notifications'
# Using Thor's indifferent hash access # Using Thor's indifferent hash access
require "thor" require 'thor'
# Core Pathname library used for traversal # Core Pathname library used for traversal
require "pathname" require 'pathname'
require "tilt" require 'tilt'
require "rack/mime" require 'rack/mime'
module Middleman module Middleman
@ -59,7 +59,7 @@ module Middleman
# Facade for ActiveSupport/Notification # Facade for ActiveSupport/Notification
def self.instrument(name, payload={}, &block) def self.instrument(name, payload={}, &block)
name << ".middleman" unless name =~ /\.middleman$/ name << '.middleman' unless name =~ /\.middleman$/
::ActiveSupport::Notifications.instrument(name, payload, &block) ::ActiveSupport::Notifications.instrument(name, payload, &block)
end end
@ -90,13 +90,13 @@ module Middleman
# @return [String] # @return [String]
def self.normalize_path(path) def self.normalize_path(path)
# The tr call works around a bug in Ruby's Unicode handling # The tr call works around a bug in Ruby's Unicode handling
path.sub(%r{^/}, "").tr('','') path.sub(%r{^/}, '').tr('','')
end end
# This is a separate method from normalize_path in case we # This is a separate method from normalize_path in case we
# change how we normalize paths # change how we normalize paths
def self.strip_leading_slash(path) def self.strip_leading_slash(path)
path.sub(%r{^/}, "") path.sub(%r{^/}, '')
end end
# Extract the text of a Rack response as a string. # Extract the text of a Rack response as a string.

View file

@ -1,5 +1,5 @@
require "middleman-core/renderers/sass" require 'middleman-core/renderers/sass'
require "compass" require 'compass'
class Middleman::CoreExtensions::Compass < ::Middleman::Extension class Middleman::CoreExtensions::Compass < ::Middleman::Extension
@ -44,7 +44,7 @@ class Middleman::CoreExtensions::Compass < ::Middleman::Extension
compass_config.output_style = :nested compass_config.output_style = :nested
# No line-comments in test mode (changing paths mess with sha1) # No line-comments in test mode (changing paths mess with sha1)
compass_config.line_comments = false if ENV["TEST"] compass_config.line_comments = false if ENV['TEST']
end end
# Call hook # Call hook

View file

@ -6,9 +6,9 @@ end
class Padrino::Helpers::OutputHelpers::ErbHandler class Padrino::Helpers::OutputHelpers::ErbHandler
# Force Erb capture not to use safebuffer # Force Erb capture not to use safebuffer
def capture_from_template(*args, &block) def capture_from_template(*args, &block)
self.output_buffer, _buf_was = "", self.output_buffer self.output_buffer, _buf_was = '', self.output_buffer
captured_block = block.call(*args) captured_block = block.call(*args)
ret = eval("@_out_buf", block.binding) ret = eval('@_out_buf', block.binding)
self.output_buffer = _buf_was self.output_buffer = _buf_was
[ ret, captured_block ] [ ret, captured_block ]
end end
@ -60,7 +60,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
def capture_html(*args, &block) def capture_html(*args, &block)
handler = auto_find_proper_handler(&block) handler = auto_find_proper_handler(&block)
captured_block, captured_html = nil, "" captured_block, captured_html = nil, ''
if handler && handler.is_type? && handler.block_is_type?(block) if handler && handler.is_type? && handler.block_is_type?(block)
captured_html, captured_block = handler.capture_from_template(*args, &block) captured_html, captured_block = handler.capture_from_template(*args, &block)
end end
@ -134,7 +134,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
parts = path.split('.').first.split('/') parts = path.split('.').first.split('/')
parts.each_with_index { |_, i| classes << parts.first(i+1).join('_') } parts.each_with_index { |_, i| classes << parts.first(i+1).join('_') }
prefix = options[:numeric_prefix] || "x" prefix = options[:numeric_prefix] || 'x'
classes.map do |c| classes.map do |c|
# Replace weird class name characters # Replace weird class name characters
c = c.gsub(/[^a-zA-Z0-9\-_]/, '-') c = c.gsub(/[^a-zA-Z0-9\-_]/, '-')
@ -162,7 +162,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
source = source.to_s.tr(' ', '') source = source.to_s.tr(' ', '')
ignore_extension = (kind == :images || kind == :fonts) # don't append extension ignore_extension = (kind == :images || kind == :fonts) # don't append extension
source << ".#{kind}" unless ignore_extension || source.end_with?(".#{kind}") source << ".#{kind}" unless ignore_extension || source.end_with?(".#{kind}")
asset_folder = "" if source.start_with?('/') # absolute path asset_folder = '' if source.start_with?('/') # absolute path
asset_url(source, asset_folder) asset_url(source, asset_folder)
end end
@ -172,7 +172,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
# @param [String] path The path (such as "photo.jpg") # @param [String] path The path (such as "photo.jpg")
# @param [String] prefix The type prefix (such as "images") # @param [String] prefix The type prefix (such as "images")
# @return [String] The fully qualified asset url # @return [String] The fully qualified asset url
def asset_url(path, prefix="") def asset_url(path, prefix='')
# Don't touch assets which already have a full path # Don't touch assets which already have a full path
if path.include?('//') or path.start_with?('data:') if path.include?('//') or path.start_with?('data:')
path path
@ -215,12 +215,12 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
options_index = block_given? ? 1 : 2 options_index = block_given? ? 1 : 2
if block_given? && args.size > 2 if block_given? && args.size > 2
raise ArgumentError.new("Too many arguments to link_to(url, options={}, &block)") raise ArgumentError.new('Too many arguments to link_to(url, options={}, &block)')
end end
if url = args[url_arg_index] if url = args[url_arg_index]
options = args[options_index] || {} options = args[options_index] || {}
raise ArgumentError.new("Options must be a hash") unless options.is_a?(Hash) raise ArgumentError.new('Options must be a hash') unless options.is_a?(Hash)
# Transform the url through our magic url_for method # Transform the url through our magic url_for method
args[url_arg_index] = url_for(url, options) args[url_arg_index] = url_for(url, options)

View file

@ -1,11 +1,11 @@
class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
option :no_fallbacks, false, "Disable I18n fallbacks" option :no_fallbacks, false, 'Disable I18n fallbacks'
option :langs, nil, "List of langs, will autodiscover by default" option :langs, nil, 'List of langs, will autodiscover by default'
option :lang_map, {}, "Language shortname map" option :lang_map, {}, 'Language shortname map'
option :path, "/:locale/", "URL prefix path" option :path, '/:locale/', 'URL prefix path'
option :templates_dir, "localizable", "Location of templates to be localized" option :templates_dir, 'localizable', 'Location of templates to be localized'
option :mount_at_root, nil, "Mount a specific language at the root of the site" option :mount_at_root, nil, 'Mount a specific language at the root of the site'
option :data, "locales", "The directory holding your locale configurations" option :data, 'locales', 'The directory holding your locale configurations'
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
@ -17,11 +17,11 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
# See https://github.com/svenfuchs/i18n/wiki/Fallbacks # See https://github.com/svenfuchs/i18n/wiki/Fallbacks
unless options[:no_fallbacks] unless options[:no_fallbacks]
require "i18n/backend/fallbacks" require 'i18n/backend/fallbacks'
::I18n::Backend::Simple.send(:include, ::I18n::Backend::Fallbacks) ::I18n::Backend::Simple.send(:include, ::I18n::Backend::Fallbacks)
end end
app.config.define_setting :locales_dir, "locales", 'The directory holding your locale configurations' app.config.define_setting :locales_dir, 'locales', 'The directory holding your locale configurations'
app.send :include, LocaleHelpers app.send :include, LocaleHelpers
end end
@ -29,7 +29,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
def after_configuration def after_configuration
app.files.reload_path(app.config[:locals_dir] || options[:data]) app.files.reload_path(app.config[:locals_dir] || options[:data])
@locales_glob = File.join(app.config[:locals_dir] || options[:data], "**", "*.{rb,yml,yaml}") @locales_glob = File.join(app.config[:locals_dir] || options[:data], '**', '*.{rb,yml,yaml}')
@locales_regex = convert_glob_to_regex(@locales_glob) @locales_regex = convert_glob_to_regex(@locales_glob)
@maps = {} @maps = {}
@ -42,7 +42,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
# Don't output localizable files # Don't output localizable files
app.ignore File.join(options[:templates_dir], "**") app.ignore File.join(options[:templates_dir], '**')
app.sitemap.provides_metadata_for_path(&method(:metadata_for_path)) app.sitemap.provides_metadata_for_path(&method(:metadata_for_path))
app.files.changed(&method(:on_file_changed)) app.files.changed(&method(:on_file_changed))
@ -75,11 +75,11 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
lang, path, page_id = result lang, path, page_id = result
new_resources << build_resource(path, resource.path, page_id, lang) new_resources << build_resource(path, resource.path, page_id, lang)
# If it's a "localizable template" # If it's a "localizable template"
elsif File.fnmatch?(File.join(options[:templates_dir], "**"), resource.path) elsif File.fnmatch?(File.join(options[:templates_dir], '**'), resource.path)
page_id = File.basename(resource.path, File.extname(resource.path)) page_id = File.basename(resource.path, File.extname(resource.path))
langs.each do |lang| langs.each do |lang|
# Remove folder name # Remove folder name
path = resource.path.sub(options[:templates_dir], "") path = resource.path.sub(options[:templates_dir], '')
new_resources << build_resource(path, resource.path, page_id, lang) new_resources << build_resource(path, resource.path, page_id, lang)
end end
end end
@ -100,7 +100,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
def convert_glob_to_regex(glob) def convert_glob_to_regex(glob)
# File.fnmatch doesn't support brackets: {rb,yml,yaml} # File.fnmatch doesn't support brackets: {rb,yml,yaml}
regex = @locales_glob.sub(/\./, '\.').sub(File.join("**", "*"), ".*").sub(/\//, '\/').sub("{rb,yml,yaml}", "(rb|ya?ml)") regex = @locales_glob.sub(/\./, '\.').sub(File.join('**', '*'), '.*').sub(/\//, '\/').sub('{rb,yml,yaml}', '(rb|ya?ml)')
%r{^#{regex}} %r{^#{regex}}
end end
@ -148,7 +148,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
known_langs = app.files.known_paths.select do |p| known_langs = app.files.known_paths.select do |p|
p.to_s.match(@locales_regex) && (p.to_s.split(File::SEPARATOR).length === 2) p.to_s.match(@locales_regex) && (p.to_s.split(File::SEPARATOR).length === 2)
end.map { |p| end.map { |p|
File.basename(p.to_s).sub(/\.ya?ml$/, "").sub(/\.rb$/, "") File.basename(p.to_s).sub(/\.ya?ml$/, '').sub(/\.rb$/, '')
}.sort.map(&:to_sym) }.sort.map(&:to_sym)
end end
end end
@ -179,10 +179,10 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
localized_page_id = ::I18n.t("paths.#{page_id}", :default => page_id, :fallback => []) localized_page_id = ::I18n.t("paths.#{page_id}", :default => page_id, :fallback => [])
prefix = if (options[:mount_at_root] == lang) || (options[:mount_at_root] == nil && langs[0] == lang) prefix = if (options[:mount_at_root] == lang) || (options[:mount_at_root] == nil && langs[0] == lang)
"/" '/'
else else
replacement = options[:lang_map].fetch(lang, lang) replacement = options[:lang_map].fetch(lang, lang)
options[:path].sub(":locale", replacement.to_s) options[:path].sub(':locale', replacement.to_s)
end end
# path needs to be changed if file has a localizable extension. (options[mount_at_root] == lang) # path needs to be changed if file has a localizable extension. (options[mount_at_root] == lang)
@ -190,7 +190,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
File.join(prefix, path.sub(page_id, localized_page_id)) File.join(prefix, path.sub(page_id, localized_page_id))
) )
path.gsub!(options[:templates_dir]+"/", "") path.gsub!(options[:templates_dir]+'/', '')
@_localization_data[path] = [lang, path, localized_page_id] @_localization_data[path] = [lang, path, localized_page_id]

View file

@ -1,6 +1,6 @@
class Middleman::Extensions::AssetHash < ::Middleman::Extension class Middleman::Extensions::AssetHash < ::Middleman::Extension
option :exts, %w(.jpg .jpeg .png .gif .js .css .otf .woff .eot .ttf .svg), "List of extensions that get asset hashes appended to them." option :exts, %w(.jpg .jpeg .png .gif .js .css .otf .woff .eot .ttf .svg), 'List of extensions that get asset hashes appended to them.'
option :ignore, [], "Regexes of filenames to skip adding asset hashes to" option :ignore, [], 'Regexes of filenames to skip adding asset hashes to'
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
@ -41,7 +41,7 @@ class Middleman::Extensions::AssetHash < ::Middleman::Extension
return if ignored_resource?(resource) return if ignored_resource?(resource)
# Render through the Rack interface so middleware and mounted apps get a shot # Render through the Rack interface so middleware and mounted apps get a shot
response = @rack_client.get(URI.escape(resource.destination_path), {}, { "bypass_asset_hash" => "true" }) response = @rack_client.get(URI.escape(resource.destination_path), {}, { 'bypass_asset_hash' => 'true' })
raise "#{resource.path} should be in the sitemap!" unless response.status == 200 raise "#{resource.path} should be in the sitemap!" unless response.status == 200
digest = Digest::SHA1.hexdigest(response.body)[0..7] digest = Digest::SHA1.hexdigest(response.body)[0..7]
@ -68,9 +68,9 @@ class Middleman::Extensions::AssetHash < ::Middleman::Extension
status, headers, response = @rack_app.call(env) status, headers, response = @rack_app.call(env)
# We don't want to use this middleware when rendering files to figure out their hash! # We don't want to use this middleware when rendering files to figure out their hash!
return [status, headers, response] if env["bypass_asset_hash"] == 'true' return [status, headers, response] if env['bypass_asset_hash'] == 'true'
path = @middleman_app.full_path(env["PATH_INFO"]) path = @middleman_app.full_path(env['PATH_INFO'])
if path =~ /(^\/$)|(\.(htm|html|php|css|js)$)/ if path =~ /(^\/$)|(\.(htm|html|php|css|js)$)/
body = ::Middleman::Util.extract_response_text(response) body = ::Middleman::Util.extract_response_text(response)

View file

@ -32,7 +32,7 @@ class Middleman::Extensions::AssetHost < ::Middleman::Extension
# @param [String] path # @param [String] path
# @param [String] prefix # @param [String] prefix
# @return [String] # @return [String]
def asset_url(path, prefix="") def asset_url(path, prefix='')
controller = extensions[:asset_host] controller = extensions[:asset_host]
original_output = super original_output = super

View file

@ -10,8 +10,8 @@ class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
# containing image name. # containing image name.
def image_tag(path) def image_tag(path)
if !path.include?("://") if !path.include?('://')
params[:alt] ||= "" params[:alt] ||= ''
real_path = path real_path = path
real_path = File.join(images_dir, real_path) unless real_path.start_with?('/') real_path = File.join(images_dir, real_path) unless real_path.start_with?('/')
@ -19,7 +19,7 @@ class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
if File.exists?(full_path) if File.exists?(full_path)
begin begin
alt_text = File.basename(full_path, ".*") alt_text = File.basename(full_path, '.*')
alt_text.capitalize! alt_text.capitalize!
params[:alt] = alt_text params[:alt] = alt_text
end end

View file

@ -5,7 +5,7 @@ class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
super super
# Include 3rd-party fastimage library # Include 3rd-party fastimage library
require "vendored-middleman-deps/fastimage" require 'vendored-middleman-deps/fastimage'
end end
helpers do helpers do
@ -16,8 +16,8 @@ class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
# @param [Hash] params # @param [Hash] params
# @return [String] # @return [String]
def image_tag(path, params={}) def image_tag(path, params={})
if !params.has_key?(:width) && !params.has_key?(:height) && !path.include?("://") if !params.has_key?(:width) && !params.has_key?(:height) && !path.include?('://')
params[:alt] ||= "" params[:alt] ||= ''
real_path = path real_path = path
real_path = File.join(images_dir, real_path) unless real_path.start_with?('/') real_path = File.join(images_dir, real_path) unless real_path.start_with?('/')

View file

@ -10,7 +10,7 @@ class Middleman::Extensions::CacheBuster < ::Middleman::Extension
real_path = real_path.path if real_path.is_a? File real_path = real_path.path if real_path.is_a? File
real_path = real_path.gsub(File.join(root, build_dir), source) real_path = real_path.gsub(File.join(root, build_dir), source)
if File.readable?(real_path) if File.readable?(real_path)
File.mtime(real_path).strftime("%s") File.mtime(real_path).strftime('%s')
else else
logger.warn "WARNING: '#{File.basename(path)}' was not found (or cannot be read) in #{File.dirname(real_path)}" logger.warn "WARNING: '#{File.basename(path)}' was not found (or cannot be read) in #{File.dirname(real_path)}"
end end
@ -22,10 +22,10 @@ class Middleman::Extensions::CacheBuster < ::Middleman::Extension
# asset_url override if we're using cache busting # asset_url override if we're using cache busting
# @param [String] path # @param [String] path
# @param [String] prefix # @param [String] prefix
def asset_url(path, prefix="") def asset_url(path, prefix='')
http_path = super http_path = super
if http_path.include?("://") || !%w(.css .png .jpg .jpeg .svg .svgz .js .gif).include?(File.extname(http_path)) if http_path.include?('://') || !%w(.css .png .jpg .jpeg .svg .svgz .js .gif).include?(File.extname(http_path))
http_path http_path
else else
if respond_to?(:http_images_path) && prefix == http_images_path if respond_to?(:http_images_path) && prefix == http_images_path
@ -37,15 +37,15 @@ class Middleman::Extensions::CacheBuster < ::Middleman::Extension
if build? if build?
real_path_dynamic = File.join(build_dir, prefix, path) real_path_dynamic = File.join(build_dir, prefix, path)
real_path_dynamic = File.expand_path(real_path_dynamic, root) real_path_dynamic = File.expand_path(real_path_dynamic, root)
http_path << "?" + File.mtime(real_path_dynamic).strftime("%s") if File.readable?(real_path_dynamic) http_path << '?' + File.mtime(real_path_dynamic).strftime('%s') if File.readable?(real_path_dynamic)
elsif resource = sitemap.find_resource_by_path(real_path_static) elsif resource = sitemap.find_resource_by_path(real_path_static)
if !resource.template? if !resource.template?
http_path << "?" + File.mtime(resource.source_file).strftime("%s") http_path << '?' + File.mtime(resource.source_file).strftime('%s')
else else
# It's a template, possible with partials. We can't really # It's a template, possible with partials. We can't really
# know when it's updated, so generate fresh cache buster every # know when it's updated, so generate fresh cache buster every
# time during developement # time during developement
http_path << "?" + Time.now.strftime("%s") http_path << '?' + Time.now.strftime('%s')
end end
end end

View file

@ -12,7 +12,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
# @param [Hash] options # @param [Hash] options
# @return [String] # @return [String]
def placekitten(size, options={}) def placekitten(size, options={})
options[:domain] = "http://placekitten.com" options[:domain] = 'http://placekitten.com'
lorem.image(size, options) lorem.image(size, options)
end end
end end
@ -110,14 +110,14 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
# Get a placeholder first name # Get a placeholder first name
# @return [String] # @return [String]
def first_name def first_name
names = "Judith Angelo Margarita Kerry Elaine Lorenzo Justice Doris Raul Liliana Kerry Elise Ciaran Johnny Moses Davion Penny Mohammed Harvey Sheryl Hudson Brendan Brooklynn Denis Sadie Trisha Jacquelyn Virgil Cindy Alexa Marianne Giselle Casey Alondra Angela Katherine Skyler Kyleigh Carly Abel Adrianna Luis Dominick Eoin Noel Ciara Roberto Skylar Brock Earl Dwayne Jackie Hamish Sienna Nolan Daren Jean Shirley Connor Geraldine Niall Kristi Monty Yvonne Tammie Zachariah Fatima Ruby Nadia Anahi Calum Peggy Alfredo Marybeth Bonnie Gordon Cara John Staci Samuel Carmen Rylee Yehudi Colm Beth Dulce Darius inley Javon Jason Perla Wayne Laila Kaleigh Maggie Don Quinn Collin Aniya Zoe Isabel Clint Leland Esmeralda Emma Madeline Byron Courtney Vanessa Terry Antoinette George Constance Preston Rolando Caleb Kenneth Lynette Carley Francesca Johnnie Jordyn Arturo Camila Skye Guy Ana Kaylin Nia Colton Bart Brendon Alvin Daryl Dirk Mya Pete Joann Uriel Alonzo Agnes Chris Alyson Paola Dora Elias Allen Jackie Eric Bonita Kelvin Emiliano Ashton Kyra Kailey Sonja Alberto Ty Summer Brayden Lori Kelly Tomas Joey Billie Katie Stephanie Danielle Alexis Jamal Kieran Lucinda Eliza Allyson Melinda Alma Piper Deana Harriet Bryce Eli Jadyn Rogelio Orlaith Janet Randal Toby Carla Lorie Caitlyn Annika Isabelle inn Ewan Maisie Michelle Grady Ida Reid Emely Tricia Beau Reese Vance Dalton Lexi Rafael Makenzie Mitzi Clinton Xena Angelina Kendrick Leslie Teddy Jerald Noelle Neil Marsha Gayle Omar Abigail Alexandra Phil Andre Billy Brenden Bianca Jared Gretchen Patrick Antonio Josephine Kyla Manuel Freya Kellie Tonia Jamie Sydney Andres Ruben Harrison Hector Clyde Wendell Kaden Ian Tracy Cathleen Shawn".split(" ") names = 'Judith Angelo Margarita Kerry Elaine Lorenzo Justice Doris Raul Liliana Kerry Elise Ciaran Johnny Moses Davion Penny Mohammed Harvey Sheryl Hudson Brendan Brooklynn Denis Sadie Trisha Jacquelyn Virgil Cindy Alexa Marianne Giselle Casey Alondra Angela Katherine Skyler Kyleigh Carly Abel Adrianna Luis Dominick Eoin Noel Ciara Roberto Skylar Brock Earl Dwayne Jackie Hamish Sienna Nolan Daren Jean Shirley Connor Geraldine Niall Kristi Monty Yvonne Tammie Zachariah Fatima Ruby Nadia Anahi Calum Peggy Alfredo Marybeth Bonnie Gordon Cara John Staci Samuel Carmen Rylee Yehudi Colm Beth Dulce Darius inley Javon Jason Perla Wayne Laila Kaleigh Maggie Don Quinn Collin Aniya Zoe Isabel Clint Leland Esmeralda Emma Madeline Byron Courtney Vanessa Terry Antoinette George Constance Preston Rolando Caleb Kenneth Lynette Carley Francesca Johnnie Jordyn Arturo Camila Skye Guy Ana Kaylin Nia Colton Bart Brendon Alvin Daryl Dirk Mya Pete Joann Uriel Alonzo Agnes Chris Alyson Paola Dora Elias Allen Jackie Eric Bonita Kelvin Emiliano Ashton Kyra Kailey Sonja Alberto Ty Summer Brayden Lori Kelly Tomas Joey Billie Katie Stephanie Danielle Alexis Jamal Kieran Lucinda Eliza Allyson Melinda Alma Piper Deana Harriet Bryce Eli Jadyn Rogelio Orlaith Janet Randal Toby Carla Lorie Caitlyn Annika Isabelle inn Ewan Maisie Michelle Grady Ida Reid Emely Tricia Beau Reese Vance Dalton Lexi Rafael Makenzie Mitzi Clinton Xena Angelina Kendrick Leslie Teddy Jerald Noelle Neil Marsha Gayle Omar Abigail Alexandra Phil Andre Billy Brenden Bianca Jared Gretchen Patrick Antonio Josephine Kyla Manuel Freya Kellie Tonia Jamie Sydney Andres Ruben Harrison Hector Clyde Wendell Kaden Ian Tracy Cathleen Shawn'.split(' ')
names[rand(names.size)] names[rand(names.size)]
end end
# Get a placeholder last name # Get a placeholder last name
# @return [String] # @return [String]
def last_name def last_name
names = "Chung Chen Melton Hill Puckett Song Hamilton Bender Wagner McLaughlin McNamara Raynor Moon Woodard Desai Wallace Lawrence Griffin Dougherty Powers May Steele Teague Vick Gallagher Solomon Walsh Monroe Connolly Hawkins Middleton Goldstein Watts Johnston Weeks Wilkerson Barton Walton Hall Ross Chung Bender Woods Mangum Joseph Rosenthal Bowden Barton Underwood Jones Baker Merritt Cross Cooper Holmes Sharpe Morgan Hoyle Allen Rich Rich Grant Proctor Diaz Graham Watkins Hinton Marsh Hewitt Branch Walton O'Brien Case Watts Christensen Parks Hardin Lucas Eason Davidson Whitehead Rose Sparks Moore Pearson Rodgers Graves Scarborough Sutton Sinclair Bowman Olsen Love McLean Christian Lamb James Chandler Stout Cowan Golden Bowling Beasley Clapp Abrams Tilley Morse Boykin Sumner Cassidy Davidson Heath Blanchard McAllister McKenzie Byrne Schroeder Griffin Gross Perkins Robertson Palmer Brady Rowe Zhang Hodge Li Bowling Justice Glass Willis Hester Floyd Graves Fischer Norman Chan Hunt Byrd Lane Kaplan Heller May Jennings Hanna Locklear Holloway Jones Glover Vick O'Donnell Goldman McKenna Starr Stone McClure Watson Monroe Abbott Singer Hall Farrell Lucas Norman Atkins Monroe Robertson Sykes Reid Chandler Finch Hobbs Adkins Kinney Whitaker Alexander Conner Waters Becker Rollins Love Adkins Black Fox Hatcher Wu Lloyd Joyce Welch Matthews Chappell MacDonald Kane Butler Pickett Bowman Barton Kennedy Branch Thornton McNeill Weinstein Middleton Moss Lucas Rich Carlton Brady Schultz Nichols Harvey Stevenson Houston Dunn West O'Brien Barr Snyder Cain Heath Boswell Olsen Pittman Weiner Petersen Davis Coleman Terrell Norman Burch Weiner Parrott Henry Gray Chang McLean Eason Weeks Siegel Puckett Heath Hoyle Garrett Neal Baker Goldman Shaffer Choi Carver".split(" ") names = "Chung Chen Melton Hill Puckett Song Hamilton Bender Wagner McLaughlin McNamara Raynor Moon Woodard Desai Wallace Lawrence Griffin Dougherty Powers May Steele Teague Vick Gallagher Solomon Walsh Monroe Connolly Hawkins Middleton Goldstein Watts Johnston Weeks Wilkerson Barton Walton Hall Ross Chung Bender Woods Mangum Joseph Rosenthal Bowden Barton Underwood Jones Baker Merritt Cross Cooper Holmes Sharpe Morgan Hoyle Allen Rich Rich Grant Proctor Diaz Graham Watkins Hinton Marsh Hewitt Branch Walton O'Brien Case Watts Christensen Parks Hardin Lucas Eason Davidson Whitehead Rose Sparks Moore Pearson Rodgers Graves Scarborough Sutton Sinclair Bowman Olsen Love McLean Christian Lamb James Chandler Stout Cowan Golden Bowling Beasley Clapp Abrams Tilley Morse Boykin Sumner Cassidy Davidson Heath Blanchard McAllister McKenzie Byrne Schroeder Griffin Gross Perkins Robertson Palmer Brady Rowe Zhang Hodge Li Bowling Justice Glass Willis Hester Floyd Graves Fischer Norman Chan Hunt Byrd Lane Kaplan Heller May Jennings Hanna Locklear Holloway Jones Glover Vick O'Donnell Goldman McKenna Starr Stone McClure Watson Monroe Abbott Singer Hall Farrell Lucas Norman Atkins Monroe Robertson Sykes Reid Chandler Finch Hobbs Adkins Kinney Whitaker Alexander Conner Waters Becker Rollins Love Adkins Black Fox Hatcher Wu Lloyd Joyce Welch Matthews Chappell MacDonald Kane Butler Pickett Bowman Barton Kennedy Branch Thornton McNeill Weinstein Middleton Moss Lucas Rich Carlton Brady Schultz Nichols Harvey Stevenson Houston Dunn West O'Brien Barr Snyder Cain Heath Boswell Olsen Pittman Weiner Petersen Davis Coleman Terrell Norman Burch Weiner Parrott Henry Gray Chang McLean Eason Weeks Siegel Puckett Heath Hoyle Garrett Neal Baker Goldman Shaffer Choi Carver".split(' ')
names[rand(names.size)] names[rand(names.size)]
end end
@ -145,7 +145,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
# @param [Hash] options # @param [Hash] options
# @return [String] # @return [String]
def image(size, options={}) def image(size, options={})
domain = options[:domain] || "http://placehold.it" domain = options[:domain] || 'http://placehold.it'
src = "#{domain}/#{size}" src = "#{domain}/#{size}"
hex = %w[a b c d e f 0 1 2 3 4 5 6 7 8 9] hex = %w[a b c d e f 0 1 2 3 4 5 6 7 8 9]
background_color = options[:background_color] background_color = options[:background_color]
@ -157,7 +157,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
end end
src << "/#{background_color.sub(/^#/, '')}" if background_color src << "/#{background_color.sub(/^#/, '')}" if background_color
src << "/ccc" if background_color.nil? && color src << '/ccc' if background_color.nil? && color
src << "/#{color.sub(/^#/, '')}" if color src << "/#{color.sub(/^#/, '')}" if color
src << "&text=#{Rack::Utils::escape(options[:text])}" if options[:text] src << "&text=#{Rack::Utils::escape(options[:text])}" if options[:text]

View file

@ -47,18 +47,18 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
def call(env) def call(env)
status, headers, response = @app.call(env) status, headers, response = @app.call(env)
if inline_html_content?(env["PATH_INFO"]) if inline_html_content?(env['PATH_INFO'])
minified = ::Middleman::Util.extract_response_text(response) minified = ::Middleman::Util.extract_response_text(response)
minified.gsub!(INLINE_CSS_REGEX) do |match| minified.gsub!(INLINE_CSS_REGEX) do |match|
$1 << @compressor.compress($2) << $3 $1 << @compressor.compress($2) << $3
end end
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s headers['Content-Length'] = ::Rack::Utils.bytesize(minified).to_s
response = [minified] response = [minified]
elsif standalone_css_content?(env["PATH_INFO"]) elsif standalone_css_content?(env['PATH_INFO'])
minified_css = @compressor.compress(::Middleman::Util.extract_response_text(response)) minified_css = @compressor.compress(::Middleman::Util.extract_response_text(response))
headers["Content-Length"] = ::Rack::Utils.bytesize(minified_css).to_s headers['Content-Length'] = ::Rack::Utils.bytesize(minified_css).to_s
response = [minified_css] response = [minified_css]
end end

View file

@ -41,7 +41,7 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
def call(env) def call(env)
status, headers, response = @app.call(env) status, headers, response = @app.call(env)
path = env["PATH_INFO"] path = env['PATH_INFO']
begin begin
if @inline && (path.end_with?('.html') || path.end_with?('.php')) if @inline && (path.end_with?('.html') || path.end_with?('.php'))
@ -49,13 +49,13 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
minified = minify_inline_content(uncompressed_source) minified = minify_inline_content(uncompressed_source)
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s headers['Content-Length'] = ::Rack::Utils.bytesize(minified).to_s
response = [minified] response = [minified]
elsif path.end_with?('.js') && @ignore.none? {|ignore| Middleman::Util.path_match(ignore, path) } elsif path.end_with?('.js') && @ignore.none? {|ignore| Middleman::Util.path_match(ignore, path) }
uncompressed_source = ::Middleman::Util.extract_response_text(response) uncompressed_source = ::Middleman::Util.extract_response_text(response)
minified = @compressor.compress(uncompressed_source) minified = @compressor.compress(uncompressed_source)
headers["Content-Length"] = ::Rack::Utils.bytesize(minified).to_s headers['Content-Length'] = ::Rack::Utils.bytesize(minified).to_s
response = [minified] response = [minified]
end end
rescue ExecJS::ProgramError => e rescue ExecJS::ProgramError => e

View file

@ -15,7 +15,7 @@ class Middleman::Extensions::RelativeAssets < ::Middleman::Extension
# @param [String] path # @param [String] path
# @param [String] prefix # @param [String] prefix
# @return [String] # @return [String]
def asset_url(path, prefix="") def asset_url(path, prefix='')
path = super(path, prefix) path = super(path, prefix)
if path.include?('//') || path.start_with?('data:') || !current_resource if path.include?('//') || path.start_with?('data:') || !current_resource

View file

@ -1,14 +1,14 @@
# SMACSS # SMACSS
class Middleman::Templates::Smacss < Middleman::Templates::Base class Middleman::Templates::Smacss < Middleman::Templates::Base
class_option "css_dir", class_option 'css_dir',
:default => "stylesheets", :default => 'stylesheets',
:desc => 'The path to the css files' :desc => 'The path to the css files'
class_option "js_dir", class_option 'js_dir',
:default => "javascripts", :default => 'javascripts',
:desc => 'The path to the javascript files' :desc => 'The path to the javascript files'
class_option "images_dir", class_option 'images_dir',
:default => "images", :default => 'images',
:desc => 'The path to the image files' :desc => 'The path to the image files'
# Template files are relative to this file # Template files are relative to this file
@ -20,9 +20,9 @@ class Middleman::Templates::Smacss < Middleman::Templates::Base
# Output the files # Output the files
# @return [void] # @return [void]
def build_scaffold! def build_scaffold!
template "shared/config.tt", File.join(location, "config.rb") template 'shared/config.tt', File.join(location, 'config.rb')
directory "smacss/source", File.join(location, "source") directory 'smacss/source', File.join(location, 'source')
empty_directory File.join(location, "source") empty_directory File.join(location, 'source')
end end
end end

View file

@ -1,4 +1,4 @@
require "middleman-core/load_paths" require 'middleman-core/load_paths'
::Middleman.setup_load_paths ::Middleman.setup_load_paths
require "middleman-core" require 'middleman-core'

View file

@ -1,5 +1,5 @@
# coding:utf-8 # coding:utf-8
RAKE_ROOT = __FILE__ RAKE_ROOT = __FILE__
GEM_NAME = "middleman" GEM_NAME = 'middleman'
require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper') require File.expand_path(File.dirname(__FILE__) + '/../gem_rake_helper')

View file

@ -1,4 +1,4 @@
require "middleman-core" require 'middleman-core'
# Make the VERSION string available # Make the VERSION string available
require "middleman-core/version" require 'middleman-core/version'