Great rubocop-ing

This commit is contained in:
Thomas Reynolds 2014-04-28 16:02:18 -07:00
parent 8f75f6516d
commit 04dc48f13d
78 changed files with 457 additions and 607 deletions

View file

@ -1,18 +1,19 @@
AllCops: AllCops:
Include: Include:
- Rakefile - '**/Rakefile'
- Gemfile - '**/Gemfile'
- config.ru - '**/config.ru'
- gem_rake_helper.rb - '**/gem_rake_helper.rb'
Exclude: Exclude:
- script/** - 'script/**/*'
- vendor/** - 'vendor/**/*'
- bin/** - '**/tmp/**/*'
- middleman-core/lib/vendored-middleman-deps/** - '**/bin/**/*'
- middleman-core/bin/** - 'middleman-core/lib/middleman-core/step_definitions/**/*'
- middleman-core/fixtures/** - 'middleman-core/lib/vendored-middleman-deps/**/*'
- middleman-core/features/** - 'middleman-core/fixtures/**/*'
- middleman-core/spec/** - 'middleman-core/features/**/*'
- 'middleman-core/spec/**/*'
LineLength: LineLength:
Enabled: false Enabled: false
MethodLength: MethodLength:
@ -24,4 +25,29 @@ Documentation:
Encoding: Encoding:
Enabled: false Enabled: false
HashSyntax: HashSyntax:
EnforcedStyle: ruby19 # EnforcedStyle: ruby19
Enabled: false
SpaceAroundEqualsInParameterDefault:
EnforcedStyle: no_space
Blocks:
Enabled: false
PerlBackrefs:
Enabled: false
ClassAndModuleChildren:
Enabled: false
AssignmentInCondition:
Enabled: false
CyclomaticComplexity:
Enabled: false
HandleExceptions:
Enabled: false
EndAlignment:
AlignWith: variable
SignalException:
Enabled: false
RegexpLiteral:
Enabled: false
FormatString:
Enabled: false
CaseIndentation:
IndentWhenRelativeTo: end

View file

@ -30,7 +30,6 @@ platforms :jruby do
end end
# Code Quality # Code Quality
gem 'cane', :platforms => [:mri_19, :mri_20], :require => false
gem 'coveralls', :require => false gem 'coveralls', :require => false
gem 'rubocop', :require => false gem 'rubocop', :require => false

View file

@ -14,41 +14,17 @@ def sh_rake(command)
sh "#{Gem.ruby} -S rake #{command}", :verbose => true sh "#{Gem.ruby} -S rake #{command}", :verbose => true
end end
def say(text, color=:magenta)
n = { :bold => 1, :red => 31, :green => 32, :yellow => 33, :blue => 34, :magenta => 35 }.fetch(color, 0)
puts "\e[%dm%s\e[0m" % [n, text]
end
desc "Run 'install' for all projects"
task :install do
GEM_PATHS.each do |dir|
Dir.chdir(dir) { sh_rake(:install) }
end
end
desc 'Clean pkg and other stuff'
task :clean do
GEM_PATHS.each do |g|
%w[tmp pkg coverage].each { |dir| sh 'rm -rf %s' % File.join(g, dir) }
end
end
desc 'Clean pkg and other stuff'
task :uninstall do
sh 'gem search --no-version middleman | grep middleman | xargs gem uninstall -a'
end
desc 'Displays the current version' desc 'Displays the current version'
task :version do task :version do
say "Current version: #{Middleman::VERSION}" puts "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 |_, 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}" puts "Updating Middleman to version #{args.version}"
File.open(version_path, 'w') { |f| f.write version_text } File.open(version_path, 'w') { |f| f.write version_text }
sh 'git commit -a -m "Bumped version to %s"' % args.version sh 'git commit -a -m "Bumped version to %s"' % args.version
end end
@ -58,7 +34,7 @@ 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...' puts '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}"
@ -66,7 +42,7 @@ end
desc 'Release all middleman gems' desc 'Release all middleman gems'
task :publish => :push do task :publish => :push do
say 'Pushing to rubygems...' puts '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
@ -94,25 +70,11 @@ task :spec do
end end
end end
begin
require 'cane/rake_task'
desc 'Run cane to check quality metrics'
Cane::RakeTask.new(:quality) do |cane|
cane.no_style = true
cane.no_doc = true
cane.abc_glob = 'middleman*/lib/middleman*/**/*.rb'
end
rescue LoadError
end
begin
require 'rubocop/rake_task' require 'rubocop/rake_task'
desc 'Run RuboCop to check code consistency' desc 'Run RuboCop to check code consistency'
Rubocop::RakeTask.new(:rubocop) do |task| Rubocop::RakeTask.new(:rubocop) do |task|
task.fail_on_error = false task.fail_on_error = false
end end
rescue LoadError
end
desc 'Run tests for all middleman gems' desc 'Run tests for all middleman gems'
task :default => :test task :default => :test

View file

@ -20,14 +20,14 @@ Cucumber::Rake::Task.new do |t|
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'

View file

@ -4,10 +4,8 @@ $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
# Top-level Middleman namespace # Top-level Middleman namespace
module Middleman module Middleman
# Backwards compatibility namespace # Backwards compatibility namespace
module Features; end module Features; end
end end
require 'middleman-core/version' require 'middleman-core/version'

View file

@ -225,7 +225,7 @@ module Middleman
def to_s def to_s
"#<Middleman::Application:0x#{object_id}>" "#<Middleman::Application:0x#{object_id}>"
end end
alias :inspect :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
# Hooks clones _hooks from the class to the instance. # Hooks clones _hooks from the class to the instance.
# https://github.com/apotonick/hooks/blob/master/lib/hooks/instance_hooks.rb#L10 # https://github.com/apotonick/hooks/blob/master/lib/hooks/instance_hooks.rb#L10

View file

@ -4,9 +4,7 @@ require 'thor/group'
# CLI Module # CLI Module
module Middleman module Middleman
module Cli module Cli
# The base task from which everything else etends # The base task from which everything else etends
class Base < Thor class Base < Thor
class << self class << self
@ -35,7 +33,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 => 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|
@ -54,7 +52,7 @@ module Middleman
def method_missing(meth, *args) def method_missing(meth, *args)
meth = meth.to_s meth = meth.to_s
if self.class.map.has_key?(meth) if self.class.map.key?(meth)
meth = self.class.map[meth] meth = self.class.map[meth]
end end
@ -63,17 +61,17 @@ module Middleman
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.exist?(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
if klass.nil? if klass.nil?
raise Thor::Error.new "There's no '#{meth}' command for Middleman. Try 'middleman help' for a list of commands." raise Thor::Error, "There's no '#{meth}' command for Middleman. Try 'middleman help' for a list of commands."
else else
args.unshift(task) if task args.unshift(task) if task
klass.start(args, :shell => self.shell) klass.start(args, :shell => shell)
end end
end end
end end

View file

@ -4,7 +4,7 @@ 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
@ -43,7 +43,7 @@ module Middleman::Cli
# Core build Thor command # Core build Thor command
# @return [void] # @return [void]
def build def build
if !ENV['MM_ROOT'] unless 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
@ -62,7 +62,7 @@ module Middleman::Cli
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.key?('glob')
opts[:clean] = options['clean'] opts[:clean] = options['clean']
self.class.shared_instance.run_hook :before_build, self self.class.shared_instance.run_hook :before_build, self
@ -71,15 +71,15 @@ module Middleman::Cli
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 had_errors && !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 shell.say msg, :red
end end
exit(1) if self.had_errors exit(1) if had_errors
end end
# Static methods # Static methods

View file

@ -1,6 +1,5 @@
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# A initializing Bundler # A initializing Bundler
class Bundle < Thor class Bundle < Thor
include Thor::Actions include Thor::Actions
@ -34,7 +33,7 @@ module Middleman::Cli
end end
# Map "u" to "upgrade" # Map "u" to "upgrade"
Base.map({ Base.map(
'u' => 'upgrade' 'u' => 'upgrade'
}) )
end end

View file

@ -1,6 +1,5 @@
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# A thor task for creating new projects # A thor task for creating new projects
class Console < Thor class Console < Thor
include Thor::Actions include Thor::Actions

View file

@ -1,6 +1,5 @@
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# A thor task for creating new projects # A thor task for creating new projects
class Extension < Thor class Extension < Thor
include Thor::Actions include Thor::Actions
@ -44,6 +43,5 @@ module Middleman::Cli
copy_file 'gitignore', File.join(name, '.gitignore') copy_file 'gitignore', File.join(name, '.gitignore')
end end
} }
end end
end end

View file

@ -2,7 +2,6 @@ require 'middleman-core/templates'
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# A thor task for creating new projects # A thor task for creating new projects
class Init < Thor class Init < Thor
check_unknown_options! check_unknown_options!
@ -45,8 +44,8 @@ module Middleman::Cli
# @param [String] name # @param [String] name
def init(name='.') def init(name='.')
key = options[:template].to_sym key = options[:template].to_sym
unless ::Middleman::Templates.registered.has_key?(key) unless ::Middleman::Templates.registered.key?(key)
raise Thor::Error.new "Unknown project template '#{key}'" raise Thor::Error, "Unknown project template '#{key}'"
end end
thor_group = ::Middleman::Templates.registered[key] thor_group = ::Middleman::Templates.registered[key]
@ -59,9 +58,9 @@ module Middleman::Cli
end end
# 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

@ -1,6 +1,5 @@
# CLI Module # CLI Module
module Middleman::Cli module Middleman::Cli
# Server thor task # Server thor task
class Server < Thor class Server < Thor
check_unknown_options! check_unknown_options!
@ -56,7 +55,7 @@ module Middleman::Cli
require 'middleman-core' require 'middleman-core'
require 'middleman-core/preview_server' require 'middleman-core/preview_server'
if !ENV['MM_ROOT'] unless 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
@ -85,5 +84,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

@ -53,7 +53,7 @@ module Middleman
# @deprecated Prefer accessing settings through "config". # @deprecated Prefer accessing settings through "config".
# #
# @return [ConfigurationManager] # @return [ConfigurationManager]
alias :settings :config alias_method :settings, :config
# Set attributes (global variables) # Set attributes (global variables)
# #
@ -143,7 +143,7 @@ module Middleman
# @param [Symbol] key # @param [Symbol] key
# @return [Boolean] # @return [Boolean]
def defines_setting?(key) def defines_setting?(key)
@settings.has_key?(key) @settings.key?(key)
end end
# Define a new setting, with optional default and user-friendly description. # Define a new setting, with optional default and user-friendly description.
@ -155,7 +155,7 @@ module Middleman
# @return [ConfigSetting] # @return [ConfigSetting]
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.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)
@ -170,7 +170,7 @@ module Middleman
# Deep duplicate of the configuration manager # Deep duplicate of the configuration manager
def dup def dup
ConfigurationManager.new.tap {|c| c.load_settings(self.all_settings) } ConfigurationManager.new.tap { |c| c.load_settings(all_settings) }
end end
# Load in a list of settings # Load in a list of settings

View file

@ -1,10 +1,8 @@
module Middleman module Middleman
module CoreExtensions module CoreExtensions
# The data extension parses YAML and JSON files in the data/ directory # The data extension parses YAML and JSON files in the data/ directory
# and makes them available to config.rb, templates and extensions # and makes them available to config.rb, templates and extensions
module Data module Data
# Extension registered # Extension registered
class << self class << self
# @private # @private
@ -16,7 +14,7 @@ module Middleman
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_method :included, :registered
end end
# Instance methods # Instance methods
@ -24,12 +22,12 @@ module Middleman
# Setup data files before anything else so they are available when # Setup data files before anything else so they are available when
# parsing config.rb # parsing config.rb
def initialize def initialize
self.files.changed DataStore.matcher do |file| files.changed DataStore.matcher do |file|
self.data.touch_file(file) if file.start_with?("#{config[:data_dir]}/") data.touch_file(file) if file.start_with?("#{config[:data_dir]}/")
end end
self.files.deleted DataStore.matcher do |file| files.deleted DataStore.matcher do |file|
self.data.remove_file(file) if file.start_with?("#{config[:data_dir]}/") data.remove_file(file) if file.start_with?("#{config[:data_dir]}/")
end end
super super
@ -45,10 +43,8 @@ module Middleman
# The core logic behind the data extension. # The core logic behind the data extension.
class DataStore class DataStore
# Static methods # Static methods
class << self class << self
# The regex which tells Middleman which files are for data # The regex which tells Middleman which files are for data
# #
# @return [Regexp] # @return [Regexp]
@ -137,7 +133,7 @@ module Middleman
data_branch = data_branch[dir] data_branch = data_branch[dir]
end end
data_branch.delete(basename) if data_branch.has_key?(basename) data_branch.delete(basename) if data_branch.key?(basename)
end end
# Get a hash from either internal static data or a callback # Get a hash from either internal static data or a callback
@ -150,10 +146,10 @@ module Middleman
@@local_sources ||= {} @@local_sources ||= {}
@@callback_sources ||= {} @@callback_sources ||= {}
if self.store.has_key?(path.to_s) if store.key?(path.to_s)
response = self.store[path.to_s] response = store[path.to_s]
elsif self.callbacks.has_key?(path.to_s) elsif callbacks.key?(path.to_s)
response = self.callbacks[path.to_s].call() response = callbacks[path.to_s].call
end end
response response
@ -164,7 +160,7 @@ module Middleman
# @param [String] path The namespace to search for # @param [String] path The namespace to search for
# @return [Hash, nil] # @return [Hash, nil]
def method_missing(path) def method_missing(path)
if @local_data.has_key?(path.to_s) if @local_data.key?(path.to_s)
return @local_data[path.to_s] return @local_data[path.to_s]
else else
result = data_for_path(path) result = data_for_path(path)
@ -179,7 +175,7 @@ module Middleman
# Needed so that method_missing makes sense # Needed so that method_missing makes sense
def respond_to?(method, include_private=false) def respond_to?(method, include_private=false)
super || has_key?(method) super || key?(method)
end end
# Make DataStore act like a hash. Return requested data, or # Make DataStore act like a hash. Return requested data, or
@ -188,24 +184,26 @@ module Middleman
# @param [String, Symbol] key The name of the data namespace # @param [String, Symbol] key The name of the data namespace
# @return [Hash, nil] # @return [Hash, nil]
def [](key) def [](key)
__send__(key) if has_key?(key) __send__(key) if key?(key)
end end
def has_key?(key) def has_key?(key)
@local_data.has_key?(key.to_s) || !!(data_for_path(key)) @local_data.key?(key.to_s) || !!(data_for_path(key))
end end
alias_method :key?, :has_key?
# Convert all the data into a static hash # Convert all the data into a static hash
# #
# @return [Hash] # @return [Hash]
def to_h def to_h
data = {} data = {}
self.store.each do |k, v| store.each do |k, _|
data[k] = data_for_path(k) data[k] = data_for_path(k)
end end
self.callbacks.each do |k, v| callbacks.each do |k, _|
data[k] = data_for_path(k) data[k] = data_for_path(k)
end end

View file

@ -32,7 +32,6 @@
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module Extensions module Extensions
# Register extension # Register extension
class << self class << self
# @private # @private
@ -51,7 +50,7 @@ module Middleman
app.send :include, InstanceMethods app.send :include, InstanceMethods
app.delegate :configure, :to => :"self.class" app.delegate :configure, :to => :"self.class"
end end
alias :included :registered alias_method :included, :registered
end end
# Class methods # Class methods
@ -75,7 +74,7 @@ module Middleman
else else
extend extension extend extension
if extension.respond_to?(:registered) if extension.respond_to?(:registered)
if extension.method(:registered).arity === 1 if extension.method(:registered).arity == 1
extension.registered(self, &block) extension.registered(self, &block)
else else
extension.registered(self, options, &block) extension.registered(self, options, &block)
@ -157,7 +156,7 @@ module Middleman
# 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.exist? 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
@ -179,7 +178,7 @@ module Middleman
run_hook :after_configuration run_hook :after_configuration
logger.debug 'Loaded extensions:' logger.debug 'Loaded extensions:'
self.extensions.each do |ext, klass| extensions.each do |ext, klass|
if ext.is_a?(Hash) if ext.is_a?(Hash)
ext.each do |k, _| ext.each do |k, _|
logger.debug "== Extension: #{k}" logger.debug "== Extension: #{k}"

View file

@ -2,16 +2,14 @@
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module ExternalHelpers module ExternalHelpers
# Setup extension # Setup extension
class << self class << self
# 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 { |filename|
basename = File.basename(filename, File.extname(filename)) basename = File.basename(filename, File.extname(filename))
basename.camelcase basename.camelcase
}, 'Proc implementing the conversion from helper filename to module name' }, 'Proc implementing the conversion from helper filename to module name'
@ -19,7 +17,7 @@ module Middleman
# After config # After config
app.after_configuration do app.after_configuration do
helpers_path = File.join(root, config[:helpers_dir]) helpers_path = File.join(root, config[:helpers_dir])
next unless File.exists?(helpers_path) next unless File.exist?(helpers_path)
Dir[File.join(helpers_path, config[:helpers_filename_glob])].each do |filename| Dir[File.join(helpers_path, config[:helpers_filename_glob])].each do |filename|
module_name = config[:helpers_filename_to_module_name_proc].call(filename) module_name = config[:helpers_filename_to_module_name_proc].call(filename)
@ -32,7 +30,7 @@ module Middleman
end end
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end

View file

@ -5,7 +5,6 @@ require 'set'
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module FileWatcher module FileWatcher
IGNORE_LIST = [ IGNORE_LIST = [
/^bin(\/|$)/, /^bin(\/|$)/,
/^\.bundle(\/|$)/, /^\.bundle(\/|$)/,
@ -26,7 +25,6 @@ module Middleman
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
app.send :include, InstanceMethods app.send :include, InstanceMethods
@ -47,12 +45,11 @@ module Middleman
files.reload_path('.') files.reload_path('.')
end end
end end
alias :included :registered alias_method :included, :registered
end end
# Instance methods # Instance methods
module InstanceMethods module InstanceMethods
# Access the file api # Access the file api
# @return [Middleman::CoreExtensions::FileWatcher::API] # @return [Middleman::CoreExtensions::FileWatcher::API]
def files def files
@ -62,7 +59,6 @@ module Middleman
# Core File Change API class # Core File Change API class
class API class API
attr_reader :app attr_reader :app
attr_reader :known_paths attr_reader :known_paths
delegate :logger, :to => :app delegate :logger, :to => :app
@ -102,7 +98,7 @@ module Middleman
path = Pathname(path) path = Pathname(path)
logger.debug "== File Change: #{path}" logger.debug "== File Change: #{path}"
@known_paths << path @known_paths << path
self.run_callbacks(path, :changed) run_callbacks(path, :changed)
end end
# Notify callbacks that a file was deleted # Notify callbacks that a file was deleted
@ -113,7 +109,7 @@ module Middleman
path = Pathname(path) path = Pathname(path)
logger.debug "== File Deletion: #{path}" logger.debug "== File Deletion: #{path}"
@known_paths.delete(path) @known_paths.delete(path)
self.run_callbacks(path, :deleted) run_callbacks(path, :deleted)
end end
# Manually trigger update events # Manually trigger update events
@ -151,7 +147,7 @@ module Middleman
def exists?(path) def exists?(path)
p = Pathname(path) p = Pathname(path)
p = p.relative_path_from(Pathname(@app.root)) if !p.relative? p = p.relative_path_from(Pathname(@app.root)) unless p.relative?
@known_paths.include?(p) @known_paths.include?(p)
end end
@ -172,7 +168,7 @@ module Middleman
# @return [void] # @return [void]
def run_callbacks(path, callbacks_name) def run_callbacks(path, callbacks_name)
path = path.to_s path = path.to_s
self.send(callbacks_name).each do |callback, matcher| send(callbacks_name).each do |callback, matcher|
next unless matcher.nil? || path.match(matcher) next unless matcher.nil? || path.match(matcher)
@app.instance_exec(path, &callback) @app.instance_exec(path, &callback)
end end

View file

@ -9,9 +9,7 @@ require 'active_support/json'
# Extensions namespace # Extensions namespace
module Middleman::CoreExtensions module Middleman::CoreExtensions
class FrontMatter < ::Middleman::Extension class FrontMatter < ::Middleman::Extension
YAML_ERRORS = [StandardError] YAML_ERRORS = [StandardError]
# https://github.com/tenderlove/psych/issues/23 # https://github.com/tenderlove/psych/issues/23

View file

@ -10,10 +10,8 @@ end
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module Rendering module Rendering
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Include methods # Include methods
@ -93,7 +91,7 @@ module Middleman
# Clean up missing Tilt exts # Clean up missing Tilt exts
app.after_configuration do app.after_configuration do
Tilt.mappings.each do |key, klasses| Tilt.mappings.each do |key, _|
begin begin
Tilt[".#{key}"] Tilt[".#{key}"]
rescue LoadError, NameError rescue LoadError, NameError
@ -103,7 +101,7 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
# Custom error class for handling # Custom error class for handling
@ -112,7 +110,6 @@ module Middleman
# Rendering instance methods # Rendering instance methods
module InstanceMethods module InstanceMethods
# Add or overwrite a default template extension # Add or overwrite a default template extension
# #
# @param [Hash] extension_map # @param [Hash] extension_map
@ -140,7 +137,7 @@ module Middleman
# Use a dup of self as a context so that instance variables set within # Use a dup of self as a context so that instance variables set within
# the template don't persist for other templates. # the template don't persist for other templates.
context = self.dup context = dup
blocks.each do |block| blocks.each do |block|
context.instance_eval(&block) context.instance_eval(&block)
end end
@ -184,7 +181,7 @@ module Middleman
# @param [String, Symbol] data # @param [String, Symbol] data
# @param [Hash] options # @param [Hash] options
# @return [String] # @return [String]
def render(engine, data, options={}, &block) def render(_, data, options={}, &block)
data = data.to_s data = data.to_s
locals = options[:locals] locals = options[:locals]
@ -198,13 +195,13 @@ module Middleman
resolve_opts[:preferred_engine] = File.extname(resource.source_file)[1..-1].to_sym resolve_opts[:preferred_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(source_dir)}/?}, ''), data)
found_partial = resolve_template(relative_dir, resolve_opts) found_partial = resolve_template(relative_dir, resolve_opts)
end end
# Look in the partials_dir for the partial with the current engine # Look in the partials_dir for the partial with the current engine
if !found_partial unless found_partial
partials_path = File.join(config[:partials_dir], data) partials_path = File.join(config[:partials_dir], data)
found_partial = resolve_template(partials_path, resolve_opts) found_partial = resolve_template(partials_path, resolve_opts)
end end
@ -317,7 +314,7 @@ module Middleman
# @return [String] # @return [String]
def fetch_layout(engine, opts) def fetch_layout(engine, opts)
# The layout name comes from either the system default or the options # The layout name comes from either the system default or the options
local_layout = opts.has_key?(:layout) ? opts[:layout] : config[:layout] local_layout = opts.key?(:layout) ? opts[:layout] : config[:layout]
return false unless local_layout return false unless local_layout
# Look for engine-specific options # Look for engine-specific options
@ -325,9 +322,9 @@ module Middleman
# The engine for the layout can be set in options, engine_options or passed # The engine for the layout can be set in options, engine_options or passed
# into this method # into this method
layout_engine = if opts.has_key?(:layout_engine) layout_engine = if opts.key?(:layout_engine)
opts[:layout_engine] opts[:layout_engine]
elsif engine_options.has_key?(:layout_engine) elsif engine_options.key?(:layout_engine)
engine_options[:layout_engine] engine_options[:layout_engine]
else else
engine engine
@ -354,11 +351,8 @@ module Middleman
# @param [Symbol] preferred_engine # @param [Symbol] preferred_engine
# @return [String] # @return [String]
def locate_layout(name, preferred_engine=nil) def locate_layout(name, preferred_engine=nil)
# Whether we've found the layout
layout_path = false
resolve_opts = {} resolve_opts = {}
resolve_opts[:preferred_engine] = preferred_engine if !preferred_engine.nil? resolve_opts[:preferred_engine] = preferred_engine unless preferred_engine.nil?
# Check layouts folder # Check layouts folder
layout_path = resolve_template(File.join(config[:layouts_dir], name.to_s), resolve_opts) layout_path = resolve_template(File.join(config[:layouts_dir], name.to_s), resolve_opts)
@ -377,13 +371,13 @@ module Middleman
# 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, current_engine)
extension = File.extname(layout_path) extension = File.extname(layout_path)
engine = extension[1..-1].to_sym engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders) # Store last engine for later (could be inside nested renders)
self.current_engine, engine_was = engine, self.current_engine self.current_engine, engine_was = engine, current_engine
begin begin
content = if block_given? content = if block_given?
@ -423,15 +417,14 @@ module Middleman
request_path = request_path.to_s request_path = request_path.to_s
cache.fetch(:resolve_template, request_path, options) do cache.fetch(:resolve_template, request_path, options) do
relative_path = Util.strip_leading_slash(request_path) relative_path = Util.strip_leading_slash(request_path)
on_disk_path = File.expand_path(relative_path, self.source_dir) on_disk_path = File.expand_path(relative_path, source_dir)
# By default, any engine will do # By default, any engine will do
preferred_engines = ['*'] preferred_engines = ['*']
# If we're specifically looking for a preferred engine # If we're specifically looking for a preferred engine
if options.has_key?(:preferred_engine) if options.key?(:preferred_engine)
extension_class = ::Tilt[options[:preferred_engine]] extension_class = ::Tilt[options[:preferred_engine]]
matched_exts = []
# Get a list of extensions for a preferred engine # Get a list of extensions for a preferred engine
matched_exts = ::Tilt.mappings.select do |ext, engines| matched_exts = ::Tilt.mappings.select do |ext, engines|
@ -464,7 +457,7 @@ module Middleman
# If we found one, return it and the found engine # If we found one, return it and the found engine
if found_path if found_path
found_path found_path
elsif File.exists?(on_disk_path) elsif File.exist?(on_disk_path)
on_disk_path on_disk_path
else else
false false

View file

@ -8,15 +8,12 @@ require 'middleman-core/util'
module Middleman module Middleman
module CoreExtensions module CoreExtensions
# Base helper to manipulate asset paths # Base helper to manipulate asset paths
module Request module Request
# Extension registered # Extension registered
class << self class << self
# @private # @private
def registered(app) def registered(app)
# CSSPIE HTC File # CSSPIE HTC File
::Rack::Mime::MIME_TYPES['.htc'] = 'text/x-component' ::Rack::Mime::MIME_TYPES['.htc'] = 'text/x-component'
@ -32,7 +29,7 @@ module Middleman
# Include instance methods # Include instance methods
app.send :include, InstanceMethods app.send :include, InstanceMethods
end end
alias :included :registered alias_method :included, :registered
end end
module ClassMethods module ClassMethods
@ -60,9 +57,7 @@ module Middleman
# @private # @private
# @param [Middleman::Application] inst # @param [Middleman::Application] inst
# @return [void] # @return [void]
def inst=(inst) attr_writer :inst
@inst = inst
end
# Return built Rack app # Return built Rack app
# #
@ -169,10 +164,10 @@ module Middleman
# @return [void] # @return [void]
def current_path=(path) def current_path=(path)
Thread.current[:current_path] = path Thread.current[:current_path] = path
Thread.current[:legacy_request] = ::Thor::CoreExt::HashWithIndifferentAccess.new({ Thread.current[:legacy_request] = ::Thor::CoreExt::HashWithIndifferentAccess.new(
:path => path, :path => path,
:params => req ? ::Thor::CoreExt::HashWithIndifferentAccess.new(req.params) : {} :params => req ? ::Thor::CoreExt::HashWithIndifferentAccess.new(req.params) : {}
}) )
end end
delegate :use, :to => :"self.class" delegate :use, :to => :"self.class"
@ -183,6 +178,7 @@ module Middleman
def req def req
Thread.current[:req] Thread.current[:req]
end end
def req=(value) def req=(value)
Thread.current[:req] = value Thread.current[:req] = value
end end
@ -199,7 +195,7 @@ module Middleman
self.req = req = ::Rack::Request.new(env) self.req = req = ::Rack::Request.new(env)
res = ::Rack::Response.new res = ::Rack::Response.new
logger.debug "== Request: #{env["PATH_INFO"]}" logger.debug "== Request: #{env['PATH_INFO']}"
# Catch :halt exceptions and use that response if given # Catch :halt exceptions and use that response if given
catch(:halt) do catch(:halt) do
@ -277,7 +273,7 @@ module Middleman
# @param [String] value Mime type # @param [String] value Mime type
# @return [void] # @return [void]
def mime_type(type, value) def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == ?. type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value ::Rack::Mime::MIME_TYPES[type] = value
end end

View file

@ -5,10 +5,8 @@ require 'rack/showexceptions'
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module ShowExceptions module ShowExceptions
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Whether to catch and display exceptions # Whether to catch and display exceptions

View file

@ -2,7 +2,6 @@ require 'active_support/core_ext/module/delegation'
require 'active_support/core_ext/class/attribute' require 'active_support/core_ext/class/attribute'
module Middleman module Middleman
class Extension class Extension
class_attribute :supports_multiple_instances, :instance_reader => false, :instance_writer => false class_attribute :supports_multiple_instances, :instance_reader => false, :instance_writer => false
class_attribute :defined_helpers, :instance_reader => false, :instance_writer => false class_attribute :defined_helpers, :instance_reader => false, :instance_writer => false
@ -34,10 +33,10 @@ module Middleman
end end
def extension_name def extension_name
self.ext_name || self.name.underscore.split('/').last.to_sym ext_name || name.underscore.split('/').last.to_sym
end end
def register(n=self.extension_name) def register(n=extension_name)
::Middleman::Extensions.register(n, self) ::Middleman::Extensions.register(n, self)
end end
@ -59,7 +58,7 @@ module Middleman
name = instance.class.extension_name name = instance.class.extension_name
return unless @_extension_activation_callbacks && @_extension_activation_callbacks[name] return unless @_extension_activation_callbacks && @_extension_activation_callbacks[name]
@_extension_activation_callbacks[name].each do |block| @_extension_activation_callbacks[name].each do |block|
block.arity == 1 ? block.call(instance) : block.call() block.arity == 1 ? block.call(instance) : block.call
end end
end end
end end
@ -142,7 +141,7 @@ module Middleman
ext = self ext = self
if ext.respond_to?(:before_build) if ext.respond_to?(:before_build)
@klass.before_build do |builder| @klass.before_build do |builder|
if ext.method(:before_build).arity === 1 if ext.method(:before_build).arity == 1
ext.before_build(builder) ext.before_build(builder)
else else
ext.before_build ext.before_build
@ -155,7 +154,7 @@ module Middleman
ext = self ext = self
if ext.respond_to?(:after_build) if ext.respond_to?(:after_build)
@klass.after_build do |builder| @klass.after_build do |builder|
if ext.method(:after_build).arity === 1 if ext.method(:after_build).arity == 1
ext.after_build(builder) ext.after_build(builder)
else else
ext.after_build ext.after_build

View file

@ -1,7 +1,5 @@
module Middleman module Middleman
module Extensions module Extensions
class << self class << self
def registered def registered
@_registered ||= {} @_registered ||= {}
@ -24,7 +22,7 @@ module Middleman
def register(name, namespace=nil, &block) def register(name, namespace=nil, &block)
# If we've already got a matching extension that passed the # If we've already got a matching extension that passed the
# version check, bail out. # version check, bail out.
return if registered.has_key?(name.to_sym) && return if registered.key?(name.to_sym) &&
!registered[name.to_sym].is_a?(String) !registered[name.to_sym].is_a?(String)
registered[name.to_sym] = if block_given? registered[name.to_sym] = if block_given?
@ -36,11 +34,11 @@ module Middleman
def load(name) def load(name)
name = name.to_sym name = name.to_sym
return nil unless registered.has_key?(name) return nil unless registered.key?(name)
extension = registered[name] extension = registered[name]
if extension.is_a?(Proc) if extension.is_a?(Proc)
extension = extension.call() || nil extension = extension.call || nil
registered[name] = extension registered[name] = extension
end end
@ -92,7 +90,7 @@ module Middleman
# @return [Boolean] Whether the file exists # @return [Boolean] Whether the file exists
def spec_has_file?(spec, path) def spec_has_file?(spec, path)
full_path = File.join(spec.full_gem_path, path) full_path = File.join(spec.full_gem_path, path)
File.exists?(full_path) File.exist?(full_path)
end end
end end
end end

View file

@ -2,7 +2,6 @@
require 'pathname' require 'pathname'
module Middleman module Middleman
class << self class << self
def setup_load_paths def setup_load_paths
@_is_setup ||= begin @_is_setup ||= begin
@ -20,12 +19,12 @@ module Middleman
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']) unless File.exist?(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
if File.exists?(ENV['BUNDLE_GEMFILE']) if File.exist?(ENV['BUNDLE_GEMFILE'])
is_bundler_setup = true is_bundler_setup = true
require 'bundler/setup' require 'bundler/setup'
end end
@ -50,7 +49,5 @@ module Middleman
return false if cwd.root? return false if cwd.root?
locate_root(cwd.parent) locate_root(cwd.parent)
end end
end end
end end

View file

@ -4,10 +4,8 @@ require 'active_support/logger'
require 'thread' require 'thread'
module Middleman module Middleman
# The Middleman Logger # The Middleman Logger
class Logger < ActiveSupport::Logger class Logger < ActiveSupport::Logger
def self.singleton(*args) def self.singleton(*args)
if !@_logger || args.length > 0 if !@_logger || args.length > 0
if args.length == 1 && (args.first.is_a?(::String) || args.first.respond_to?(:write)) if args.length == 1 && (args.first.is_a?(::String) || args.first.respond_to?(:write))
@ -42,7 +40,7 @@ module Middleman
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" info "== Instrument (#{evt.name.sub(/.middleman$/, '')}): #{evt.duration}ms"
end end
end end
end end

View file

@ -40,12 +40,12 @@ module Middleman
end end
# The index page # The index page
def index(env) def index(_)
template('index.html.erb') template('index.html.erb')
end end
# Inspect the sitemap # Inspect the sitemap
def sitemap(env) def sitemap(_)
resources = @middleman.inst.sitemap.resources(true) resources = @middleman.inst.sitemap.resources(true)
sitemap_tree = SitemapTree.new sitemap_tree = SitemapTree.new
@ -58,7 +58,7 @@ module Middleman
end end
# Inspect configuration # Inspect configuration
def config(env) def config(_)
global_config = @middleman.inst.config.all_settings.map { |c| ConfigSetting.new(c) } global_config = @middleman.inst.config.all_settings.map { |c| ConfigSetting.new(c) }
extension_config = {} extension_config = {}

View file

@ -4,7 +4,6 @@ require 'middleman-core/logger'
module Middleman module Middleman
module PreviewServer module PreviewServer
DEFAULT_PORT = 4567 DEFAULT_PORT = 4567
class << self class << self
@ -70,7 +69,7 @@ module Middleman
begin begin
app = new_app app = new_app
rescue Exception => e rescue => 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

View file

@ -1,6 +1,5 @@
module Middleman module Middleman
module Profiling module Profiling
# The profiler instance. There can only be one! # The profiler instance. There can only be one!
def self.profiler=(prof) def self.profiler=(prof)
@profiler = prof @profiler = prof
@ -31,12 +30,10 @@ module Middleman
# A profiler that uses ruby-prof # A profiler that uses ruby-prof
class RubyProfProfiler class RubyProfProfiler
def initialize def initialize
begin
require 'ruby-prof' require 'ruby-prof'
rescue LoadError rescue LoadError
raise "To use the --profile option, you must add the 'ruby-prof' gem to your Gemfile" raise "To use the --profile option, you must add the 'ruby-prof' gem to your Gemfile"
end end
end
def start def start
RubyProf.start RubyProf.start

View file

@ -4,7 +4,6 @@ module Middleman
module Renderers module Renderers
module AsciiDoc module AsciiDoc
class << self class << self
def registered(app) def registered(app)
app.config.define_setting :asciidoc, { app.config.define_setting :asciidoc, {
:safe => :safe, :safe => :safe,
@ -35,7 +34,7 @@ module Middleman
opts[:layout] = layout opts[:layout] = layout
end end
end end
opts[:layout_engine] = (doc.attr 'page-layout-engine') if (doc.attr? 'page-layout-engine') opts[:layout_engine] = (doc.attr 'page-layout-engine') if doc.attr? 'page-layout-engine'
# TODO override attributes to set docfile, docdir, docname, etc # TODO override attributes to set docfile, docdir, docname, etc
# alternative is to set :renderer_options, which get merged into options by the rendering extension # alternative is to set :renderer_options, which get merged into options by the rendering extension
# opts[:attributes] = config[:asciidoc][:attributes].dup # opts[:attributes] = config[:asciidoc][:attributes].dup
@ -52,7 +51,7 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end

View file

@ -3,10 +3,8 @@ require 'coffee_script'
module Middleman module Middleman
module Renderers module Renderers
# CoffeeScript Renderer # CoffeeScript Renderer
module CoffeeScript module CoffeeScript
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
@ -20,7 +18,7 @@ module Middleman
DebuggingCoffeeScriptTemplate.middleman_app = self DebuggingCoffeeScriptTemplate.middleman_app = self
end end
end end
alias :included :registered alias_method :included, :registered
end end
# A Template for Tilt which outputs debug messages # A Template for Tilt which outputs debug messages

View file

@ -4,7 +4,6 @@ module Middleman
module ERb module ERb
# Setup extension # Setup extension
class << self class << self
# once registered # once registered
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
@ -16,7 +15,7 @@ module Middleman
::Tilt.prefer(Template, :erb) ::Tilt.prefer(Template, :erb)
end end
end end
alias :included :registered alias_method :included, :registered
end end
class Template < ::Tilt::ErubisTemplate class Template < ::Tilt::ErubisTemplate

View file

@ -13,10 +13,8 @@ end
module Middleman module Middleman
module Renderers module Renderers
# Haml Renderer # Haml Renderer
module Haml module Haml
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
@ -33,7 +31,7 @@ module Middleman
init_haml_helpers init_haml_helpers
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end

View file

@ -2,7 +2,6 @@ require 'kramdown'
module Middleman module Middleman
module Renderers module Renderers
# Our own Kramdown Tilt template that simply uses our custom renderer. # Our own Kramdown Tilt template that simply uses our custom renderer.
class KramdownTemplate < ::Tilt::KramdownTemplate class KramdownTemplate < ::Tilt::KramdownTemplate
def evaluate(scope, locals, &block) def evaluate(scope, locals, &block)
@ -32,7 +31,7 @@ module Middleman
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
attr = el.attr.dup attr = el.attr.dup

View file

@ -2,13 +2,10 @@ require 'less'
module Middleman module Middleman
module Renderers module Renderers
# Sass renderer # Sass renderer
module Less module Less
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Default less options # Default less options
@ -27,12 +24,11 @@ module Middleman
::Tilt.prefer(LocalLoadingLessTemplate) ::Tilt.prefer(LocalLoadingLessTemplate)
end end
alias :included :registered alias_method :included, :registered
end end
# A SassTemplate for Tilt which outputs debug messages # A SassTemplate for Tilt which outputs debug messages
class LocalLoadingLessTemplate < ::Tilt::LessTemplate class LocalLoadingLessTemplate < ::Tilt::LessTemplate
def prepare def prepare
if ::Less.const_defined? :Engine if ::Less.const_defined? :Engine
@engine = ::Less::Engine.new(data) @engine = ::Less::Engine.new(data)
@ -41,9 +37,7 @@ module Middleman
@engine = parser.parse(data) @engine = parser.parse(data)
end end
end end
end
end
end end
end end
end end

View file

@ -3,13 +3,10 @@ require 'liquid'
module Middleman module Middleman
module Renderers module Renderers
# Liquid Renderer # Liquid Renderer
module Liquid module Liquid
# Setup extension # Setup extension
class << self class << self
# Once registerd # Once registerd
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
@ -27,9 +24,8 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end
end end

View file

@ -1,12 +1,9 @@
module Middleman module Middleman
module Renderers module Renderers
# Markdown renderer # Markdown renderer
module Markdown module Markdown
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Set our preference for a markdown engine # Set our preference for a markdown engine
@ -35,7 +32,7 @@ module Middleman
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]
# 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
@ -58,9 +55,8 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end
end end

View file

@ -2,9 +2,7 @@ require 'redcarpet'
module Middleman module Middleman
module Renderers module Renderers
class RedcarpetTemplate < ::Tilt::RedcarpetTemplate::Redcarpet2 class RedcarpetTemplate < ::Tilt::RedcarpetTemplate::Redcarpet2
# because tilt has decided to convert these # because tilt has decided to convert these
# in the wrong direction # in the wrong direction
ALIASES = { ALIASES = {
@ -15,7 +13,7 @@ module Middleman
# Don't overload :renderer option with smartypants # Don't overload :renderer option with smartypants
# Support renderer-level options # Support renderer-level options
def generate_renderer def generate_renderer
return options.delete(:renderer) if options.has_key?(:renderer) return options.delete(:renderer) if options.key?(:renderer)
covert_options_to_aliases! covert_options_to_aliases!
@ -32,8 +30,8 @@ module Middleman
# Renderer Options # Renderer Options
possible_render_opts = [:filter_html, :no_images, :no_links, :no_styles, :safe_links_only, :with_toc_data, :hard_wrap, :xhtml, :prettify, :link_attributes] possible_render_opts = [:filter_html, :no_images, :no_links, :no_styles, :safe_links_only, :with_toc_data, :hard_wrap, :xhtml, :prettify, :link_attributes]
render_options = possible_render_opts.inject({}) do |sum, opt| render_options = possible_render_opts.reduce({}) do |sum, opt|
sum[opt] = options.delete(opt) if options.has_key?(opt) sum[opt] = options.delete(opt) if options.key?(opt)
sum sum
end end
@ -44,7 +42,7 @@ module Middleman
def covert_options_to_aliases! def covert_options_to_aliases!
ALIASES.each do |aka, actual| ALIASES.each do |aka, actual|
options[actual] = options.delete(aka) if options.has_key? aka options[actual] = options.delete(aka) if options.key? aka
end end
end end
end end
@ -64,7 +62,7 @@ module Middleman
middleman_app.image_tag(link, :title => title, :alt => alt_text) middleman_app.image_tag(link, :title => title, :alt => alt_text)
else else
link_string = link.dup link_string = link.dup
link_string << %Q{"#{title}"} if title && title.length > 0 && title != alt_text link_string << %Q("#{title}") if title && title.length > 0 && title != alt_text
%Q{![#{alt_text}](#{link_string})} %Q{![#{alt_text}](#{link_string})}
end end
end end
@ -77,7 +75,7 @@ module Middleman
middleman_app.link_to(content, link, attributes) middleman_app.link_to(content, link, attributes)
else else
link_string = link.dup link_string = link.dup
link_string << %Q{"#{title}"} if title && title.length > 0 && title != alt_text link_string << %Q("#{title}") if title && title.length > 0 && title != alt_text
%Q{[#{content}](#{link_string})} %Q{[#{content}](#{link_string})}
end end
end end

View file

@ -3,13 +3,10 @@ require 'compass/import-once'
module Middleman module Middleman
module Renderers module Renderers
# Sass renderer # Sass renderer
module Sass module Sass
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Default sass options # Default sass options
@ -31,16 +28,15 @@ module Middleman
::Compass::ImportOnce.activate! ::Compass::ImportOnce.activate!
end end
alias :included :registered alias_method :included, :registered
end end
# A SassTemplate for Tilt which outputs debug messages # A SassTemplate for Tilt which outputs debug messages
class SassPlusCSSFilenameTemplate < ::Tilt::SassTemplate class SassPlusCSSFilenameTemplate < ::Tilt::SassTemplate
def initialize(*args, &block) def initialize(*args, &block)
super super
if @options.has_key?(:context) if @options.key?(:context)
@context = @options[:context] @context = @options[:context]
end end
end end
@ -87,7 +83,6 @@ module Middleman
# SCSS version of the above template # SCSS version of the above template
class ScssPlusCSSFilenameTemplate < SassPlusCSSFilenameTemplate class ScssPlusCSSFilenameTemplate < SassPlusCSSFilenameTemplate
# Define the expected syntax for the template # Define the expected syntax for the template
# @return [Symbol] # @return [Symbol]
def syntax def syntax

View file

@ -17,13 +17,10 @@ end
module Middleman module Middleman
module Renderers module Renderers
# Slim renderer # Slim renderer
module Slim module Slim
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
@ -50,7 +47,7 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end

View file

@ -3,13 +3,10 @@ require 'stylus/tilt'
module Middleman module Middleman
module Renderers module Renderers
# Sass renderer # Sass renderer
module Stylus module Stylus
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Default less options # Default less options
@ -20,9 +17,8 @@ module Middleman
end end
end end
alias :included :registered alias_method :included, :registered
end end
end end
end end
end end

View file

@ -9,15 +9,11 @@ require 'middleman-core/sitemap/extensions/ignores'
# Core Sitemap Extensions # Core Sitemap Extensions
module Middleman module Middleman
module Sitemap module Sitemap
# Setup Extension # Setup Extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
app.register Middleman::Sitemap::Extensions::RequestEndpoints app.register Middleman::Sitemap::Extensions::RequestEndpoints
app.register Middleman::Sitemap::Extensions::Proxies app.register Middleman::Sitemap::Extensions::Proxies
app.register Middleman::Sitemap::Extensions::Ignores app.register Middleman::Sitemap::Extensions::Ignores
@ -39,8 +35,8 @@ module Middleman
# Files starting with an underscore, but not a double-underscore # Files starting with an underscore, but not a double-underscore
:partials => proc { |file| file =~ %r{/_[^_]} }, :partials => proc { |file| file =~ %r{/_[^_]} },
:layout => proc { |file, app| :layout => proc { |file, sitemap_app|
file.start_with?(File.join(app.config[:source], 'layout.')) || file.start_with?(File.join(app.config[:source], 'layouts/')) file.start_with?(File.join(sitemap_app.config[:source], 'layout.')) || file.start_with?(File.join(sitemap_app.config[:source], 'layouts/'))
} }
}, 'Callbacks that can exclude paths from the sitemap' }, 'Callbacks that can exclude paths from the sitemap'
@ -52,13 +48,11 @@ module Middleman
sitemap sitemap
end end
end end
alias :included :registered alias_method :included, :registered
end end
# Sitemap instance methods # Sitemap instance methods
module InstanceMethods module InstanceMethods
# Get the sitemap class instance # Get the sitemap class instance
# @return [Middleman::Sitemap::Store] # @return [Middleman::Sitemap::Store]
def sitemap def sitemap
@ -77,7 +71,6 @@ module Middleman
return nil unless current_path return nil unless current_path
sitemap.find_resource_by_destination_path(current_path) sitemap.find_resource_by_destination_path(current_path)
end end
end end
end end
end end

View file

@ -1,14 +1,9 @@
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
module Ignores module Ignores
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Include methods # Include methods
@ -17,12 +12,11 @@ module Middleman
::Middleman::Sitemap::Resource.send :include, ResourceInstanceMethods ::Middleman::Sitemap::Resource.send :include, ResourceInstanceMethods
end end
alias :included :registered alias_method :included, :registered
end end
# Helpers methods for Resources # Helpers methods for Resources
module ResourceInstanceMethods module ResourceInstanceMethods
# Whether the Resource is ignored # Whether the Resource is ignored
# @return [Boolean] # @return [Boolean]
def ignored? def ignored?
@ -61,15 +55,15 @@ module Middleman
# @return [void] # @return [void]
def ignore(path=nil, &block) def ignore(path=nil, &block)
if path.is_a? Regexp if path.is_a? Regexp
@ignored_callbacks << Proc.new {|p| p =~ path } @ignored_callbacks << proc { |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 { |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
return if ignored?(path_clean) return if ignored?(path_clean)
@ignored_callbacks << Proc.new {|p| p == path_clean } @ignored_callbacks << proc { |p| p == path_clean }
end end
elsif block_given? elsif block_given?
@ignored_callbacks << block @ignored_callbacks << block

View file

@ -1,13 +1,9 @@
require 'set' require 'set'
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
class OnDisk class OnDisk
attr_accessor :sitemap attr_accessor :sitemap
attr_accessor :waiting_for_ready attr_accessor :waiting_for_ready

View file

@ -1,14 +1,9 @@
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
module Proxies module Proxies
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
::Middleman::Sitemap::Resource.send :include, ResourceInstanceMethods ::Middleman::Sitemap::Resource.send :include, ResourceInstanceMethods
@ -17,7 +12,7 @@ module Middleman
app.send :include, InstanceMethods app.send :include, InstanceMethods
end end
alias :included :registered alias_method :included, :registered
end end
module ResourceInstanceMethods module ResourceInstanceMethods
@ -38,9 +33,7 @@ module Middleman
# The path of the page this page is proxied to, or nil if it's not proxied. # The path of the page this page is proxied to, or nil if it's not proxied.
# @return [String] # @return [String]
def proxied_to attr_reader :proxied_to
@proxied_to
end
# The resource for the page this page is proxied to. Throws an exception # The resource for the page this page is proxied to. Throws an exception
# if there is no resource. # if there is no resource.

View file

@ -1,21 +1,16 @@
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
module Redirects module Redirects
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Include methods # Include methods
app.send :include, InstanceMethods app.send :include, InstanceMethods
end end
alias :included :registered alias_method :included, :registered
end end
module InstanceMethods module InstanceMethods
@ -78,10 +73,10 @@ module Middleman
end end
def render(*args, &block) def render(*args, &block)
url = ::Middleman::Util.url_for(store.app, @request_path, { url = ::Middleman::Util.url_for(store.app, @request_path,
:relative => false, :relative => false,
:find_resource => true :find_resource => true
}) )
if output if output
output.call(path, url) output.call(path, url)
@ -119,7 +114,6 @@ module Middleman
def metadata def metadata
@local_metadata.dup @local_metadata.dup
end end
end end
end end
end end

View file

@ -1,21 +1,16 @@
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
module RequestEndpoints module RequestEndpoints
# Setup extension # Setup extension
class << self class << self
# Once registered # Once registered
def registered(app) def registered(app)
# Include methods # Include methods
app.send :include, InstanceMethods app.send :include, InstanceMethods
end end
alias :included :registered alias_method :included, :registered
end end
module InstanceMethods module InstanceMethods
@ -48,7 +43,7 @@ module Middleman
if block_given? if block_given?
endpoint[:output] = block endpoint[:output] = block
else else
endpoint[:request_path] = opts[:path] if opts.has_key?(:path) endpoint[:request_path] = opts[:path] if opts.key?(:path)
end end
@endpoints[path] = endpoint @endpoints[path] = endpoint
@ -65,7 +60,7 @@ module Middleman
path, path,
config[:request_path] config[:request_path]
) )
r.output = config[:output] if config.has_key?(:output) r.output = config[:output] if config.key?(:output)
r r
end end
end end
@ -85,12 +80,10 @@ module Middleman
end end
def render(*args, &block) def render(*args, &block)
return self.output.call if self.output return output.call if output
end end
def request_path attr_reader :request_path
@request_path
end
def binary? def binary?
false false
@ -107,7 +100,6 @@ module Middleman
def metadata def metadata
@local_metadata.dup @local_metadata.dup
end end
end end
end end
end end

View file

@ -1,9 +1,6 @@
module Middleman module Middleman
module Sitemap module Sitemap
module Extensions module Extensions
module Traversal module Traversal
# This resource's parent resource # This resource's parent resource
# @return [Middleman::Sitemap::Resource, nil] # @return [Middleman::Sitemap::Resource, nil]
@ -28,14 +25,14 @@ module Middleman
if eponymous_directory? if eponymous_directory?
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
store.resources.select do |sub_resource| store.resources.select do |sub_resource|
if sub_resource.path == self.path || sub_resource.path !~ prefix if sub_resource.path == path || sub_resource.path !~ prefix
false false
else else
inner_path = sub_resource.path.sub(prefix, '') inner_path = sub_resource.path.sub(prefix, '')
@ -72,7 +69,7 @@ module Middleman
return true return true
end end
full_path = File.join(app.source_dir, eponymous_directory_path) full_path = File.join(app.source_dir, eponymous_directory_path)
!!(File.exists?(full_path) && File.directory?(full_path)) !!(File.exist?(full_path) && File.directory?(full_path))
end end
# The path for this resource if it were a directory, and not a file # The path for this resource if it were a directory, and not a file

View file

@ -2,7 +2,6 @@ require 'active_support/core_ext/object/inclusion'
module Middleman module Middleman
module Sitemap module Sitemap
# Code adapted from https://github.com/ralph/document_mapper/ # Code adapted from https://github.com/ralph/document_mapper/
module Queryable module Queryable
OPERATOR_MAPPING = { OPERATOR_MAPPING = {
@ -25,7 +24,7 @@ module Middleman
documents = resources.select { |r| !r.raw_data.empty? } documents = resources.select { |r| !r.raw_data.empty? }
options[:where].each do |selector, selector_value| options[:where].each do |selector, selector_value|
documents = documents.select do |document| documents = documents.select do |document|
next unless document.raw_data.has_key? selector.attribute next unless document.raw_data.key? selector.attribute
document_value = document.raw_data[selector.attribute] document_value = document.raw_data[selector.attribute]
operator = OPERATOR_MAPPING[selector.operator] operator = OPERATOR_MAPPING[selector.operator]
document_value.send operator, selector_value document_value.send operator, selector_value
@ -78,12 +77,12 @@ module Middleman
symbol_hash = constraints_hash.reject { |key, value| key.is_a? Selector } symbol_hash = constraints_hash.reject { |key, value| key.is_a? Selector }
symbol_hash.each do |attribute, value| symbol_hash.each do |attribute, value|
selector = Selector.new(:attribute => attribute, :operator => 'equal') selector = Selector.new(:attribute => attribute, :operator => 'equal')
selector_hash.update({ selector => value }) selector_hash.update(selector => value)
end end
Query.new @model, opts(:where => @where.merge(selector_hash)) Query.new @model, opts(:where => @where.merge(selector_hash))
end end
def opts new_opts def opts(new_opts)
{ :where => {}.merge(@where), { :where => {}.merge(@where),
:order_by => @order_by, :order_by => @order_by,
:offset => @offset, :offset => @offset,
@ -104,11 +103,11 @@ module Middleman
end end
def first def first
self.all.first all.first
end end
def last def last
self.all.last all.last
end end
def all def all
@ -149,7 +148,7 @@ class Symbol
unless method_defined?(:"<=>") unless method_defined?(:"<=>")
def <=>(other) def <=>(other)
self.to_s <=> other.to_s to_s <=> other.to_s
end end
end end
end end

View file

@ -2,10 +2,8 @@ require 'middleman-core/sitemap/extensions/traversal'
require 'middleman-core/sitemap/extensions/content_type' require 'middleman-core/sitemap/extensions/content_type'
module Middleman module Middleman
# Sitemap namespace # Sitemap namespace
module Sitemap module Sitemap
# Sitemap Resource class # Sitemap Resource class
class Resource class Resource
include Middleman::Sitemap::Extensions::Traversal include Middleman::Sitemap::Extensions::Traversal
@ -62,13 +60,13 @@ module Middleman
result = store.metadata_for_path(path).dup result = store.metadata_for_path(path).dup
file_meta = store.metadata_for_file(source_file).dup file_meta = store.metadata_for_file(source_file).dup
if file_meta.has_key?(:blocks) if file_meta.key?(:blocks)
result[:blocks] += file_meta.delete(:blocks) result[:blocks] += file_meta.delete(:blocks)
end end
result.deep_merge!(file_meta) result.deep_merge!(file_meta)
local_meta = @local_metadata.dup local_meta = @local_metadata.dup
if local_meta.has_key?(:blocks) if local_meta.key?(:blocks)
result[:blocks] += local_meta.delete(:blocks) result[:blocks] += local_meta.delete(:blocks)
end end
result.deep_merge!(local_meta) result.deep_merge!(local_meta)
@ -81,7 +79,7 @@ module Middleman
# @param [Hash] metadata A metadata block like provides_metadata_for_path takes # @param [Hash] metadata A metadata block like provides_metadata_for_path takes
def add_metadata(metadata={}, &block) def add_metadata(metadata={}, &block)
metadata = metadata.dup metadata = metadata.dup
if metadata.has_key?(:blocks) if metadata.key?(:blocks)
@local_metadata[:blocks] += metadata.delete(:blocks) @local_metadata[:blocks] += metadata.delete(:blocks)
end end
@local_metadata.deep_merge!(metadata) @local_metadata.deep_merge!(metadata)
@ -99,13 +97,13 @@ module Middleman
end end
def request_path def request_path
self.destination_path destination_path
end end
# Render this resource # Render this resource
# @return [String] # @return [String]
def render(opts={}, locs={}, &block) def render(opts={}, locs={}, &block)
if !template? unless template?
return app.template_data_for_file(source_file) return app.template_data_for_file(source_file)
end end
@ -126,18 +124,18 @@ module Middleman
locs = md[:locals].deep_merge(locs) locs = md[:locals].deep_merge(locs)
# Forward remaining data to helpers # Forward remaining data to helpers
if md.has_key?(:page) if md.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
blocks << block if block_given? blocks << block if block_given?
app.current_path ||= self.destination_path app.current_path ||= destination_path
# Certain output file types don't use layouts # Certain output file types don't use layouts
if !opts.has_key?(:layout) unless opts.key?(:layout)
opts[:layout] = false if %w(.js .json .css .txt).include?(self.ext) opts[:layout] = false if %w(.js .json .css .txt).include?(ext)
end end
app.render_template(source_file, locs, opts, blocks) app.render_template(source_file, locs, opts, blocks)

View file

@ -4,10 +4,8 @@ require 'monitor'
require 'middleman-core/sitemap/queryable' require 'middleman-core/sitemap/queryable'
module Middleman module Middleman
# Sitemap namespace # Sitemap namespace
module Sitemap module Sitemap
# The Store class # The Store class
# #
# The Store manages a collection of Resource objects, which represent # The Store manages a collection of Resource objects, which represent
@ -15,7 +13,6 @@ module Middleman
# which is the path relative to the source directory, minus any template # which is the path relative to the source directory, minus any template
# extensions. All "path" parameters used in this class are source paths. # extensions. All "path" parameters used in this class are source paths.
class Store class Store
# @return [Middleman::Application] # @return [Middleman::Application]
attr_accessor :app attr_accessor :app
@ -122,12 +119,12 @@ module Middleman
def metadata_for_file(source_file) def metadata_for_file(source_file)
blank_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] } blank_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] }
provides_metadata.inject(blank_metadata) do |result, (callback, matcher)| provides_metadata.reduce(blank_metadata) do |result, (callback, matcher)|
next result if matcher && !source_file.match(matcher) next result if matcher && !source_file.match(matcher)
metadata = callback.call(source_file).dup metadata = callback.call(source_file).dup
if metadata.has_key?(:blocks) if metadata.key?(:blocks)
result[:blocks] << metadata[:blocks] result[:blocks] << metadata[:blocks]
metadata.delete(:blocks) metadata.delete(:blocks)
end end
@ -156,7 +153,7 @@ module Middleman
blank_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] } blank_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] }
@_cached_metadata[request_path] = provides_metadata_for_path.inject(blank_metadata) do |result, (callback, matcher)| @_cached_metadata[request_path] = provides_metadata_for_path.reduce(blank_metadata) do |result, (callback, matcher)|
case matcher case matcher
when Regexp when Regexp
next result unless request_path =~ matcher next result unless request_path =~ matcher
@ -213,7 +210,7 @@ module Middleman
@app.logger.debug '== Rebuilding resource list' @app.logger.debug '== Rebuilding resource list'
@resources = @resource_list_manipulators.inject([]) do |result, (_, inst)| @resources = @resource_list_manipulators.reduce([]) do |result, (_, inst)|
newres = inst.manipulate_resource_list(result) newres = inst.manipulate_resource_list(result)
# Reset lookup cache # Reset lookup cache
@ -269,9 +266,9 @@ module Middleman
def find_extension(path, file) def find_extension(path, file)
input_ext = File.extname(file) input_ext = File.extname(file)
if !input_ext.empty? unless 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.key?(input_ext)
path << ".#{@app.template_extensions[input_ext]}" path << ".#{@app.template_extensions[input_ext]}"
end end
end end

View file

@ -4,10 +4,8 @@ require 'thor/group'
# Templates namespace # Templates namespace
module Middleman::Templates module Middleman::Templates
# Static methods # Static methods
class << self class << self
# Get list of registered templates and add new ones # Get list of registered templates and add new ones
# #
# Middleman::Templates.register(:ext_name, klass) # Middleman::Templates.register(:ext_name, klass)
@ -22,7 +20,7 @@ module Middleman::Templates
end end
# Middleman::Templates.register(name, klass) # Middleman::Templates.register(name, klass)
alias :registered :register alias_method :registered, :register
end end
# Base Template class. Handles basic options and paths. # Base Template class. Handles basic options and paths.

View file

@ -1,6 +1,5 @@
# 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'

View file

@ -1,6 +1,5 @@
# A barebones template with nothing much in it # A barebones template with nothing much in it
class Middleman::Templates::Empty < Middleman::Templates::Base class Middleman::Templates::Empty < Middleman::Templates::Base
# 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

View file

@ -28,7 +28,6 @@ class MyExtension < ::Middleman::Extension
# def a_helper # def a_helper
# end # end
# end # end
end end
# Register extensions which can be activated # Register extensions which can be activated

View file

@ -1,6 +1,5 @@
# 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'

View file

@ -1,6 +1,5 @@
# Local templates # Local templates
class Middleman::Templates::Local < Middleman::Templates::Base 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
@ -20,7 +19,7 @@ Dir[File.join(Middleman::Templates::Local.source_root, '*')].each do |dir|
template_file = File.join(dir, 'template.rb') template_file = File.join(dir, 'template.rb')
if File.exists?(template_file) if File.exist?(template_file)
require template_file require template_file
else else
Middleman::Templates.register(File.basename(dir).to_sym, Middleman::Templates::Local) Middleman::Templates.register(File.basename(dir).to_sym, Middleman::Templates::Local)

View file

@ -1,6 +1,5 @@
# Mobile HTML5 Boilerplate # Mobile HTML5 Boilerplate
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'

View file

@ -14,7 +14,6 @@ require 'rack/mime'
module Middleman module Middleman
module Util module Util
class << self class << self
# Whether the source file is binary. # Whether the source file is binary.
# #
# @param [String] filename The file to check. # @param [String] filename The file to check.
@ -27,7 +26,7 @@ module Middleman
return false if Tilt.registered?(ext.sub('.', '')) return false if Tilt.registered?(ext.sub('.', ''))
dot_ext = (ext.to_s[0] == ?.) ? ext.dup : ".#{ext}" dot_ext = (ext.to_s[0] == '.') ? ext.dup : ".#{ext}"
if mime = ::Rack::Mime.mime_type(dot_ext, nil) if mime = ::Rack::Mime.mime_type(dot_ext, nil)
!nonbinary_mime?(mime) !nonbinary_mime?(mime)
@ -85,7 +84,7 @@ module Middleman
def extract_response_text(response) def extract_response_text(response)
# The rack spec states all response bodies must respond to each # The rack spec states all response bodies must respond to each
result = '' result = ''
response.each do |part, s| response.each do |part, _|
result << part result << part
end end
result result
@ -210,7 +209,7 @@ module Middleman
def full_path(path, app) def full_path(path, app)
resource = app.sitemap.find_resource_by_destination_path(path) resource = app.sitemap.find_resource_by_destination_path(path)
if !resource unless resource
# Try it with /index.html at the end # Try it with /index.html at the end
indexed_path = File.join(path.sub(%r{/$}, ''), app.config[:index_file]) indexed_path = File.join(path.sub(%r{/$}, ''), app.config[:index_file])
resource = app.sitemap.find_resource_by_destination_path(indexed_path) resource = app.sitemap.find_resource_by_destination_path(indexed_path)

View file

@ -2,7 +2,6 @@ require 'middleman-core/renderers/sass'
require 'compass' require 'compass'
class Middleman::CoreExtensions::Compass < ::Middleman::Extension class Middleman::CoreExtensions::Compass < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super

View file

@ -7,7 +7,7 @@ require 'padrino-helpers'
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 = '', output_buffer
raw = block.call(*args) raw = block.call(*args)
captured = template.instance_variable_get(:@_out_buf) captured = template.instance_variable_get(:@_out_buf)
self.output_buffer = _buf_was self.output_buffer = _buf_was
@ -16,7 +16,6 @@ class Padrino::Helpers::OutputHelpers::ErbHandler
end end
class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
@ -108,8 +107,10 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
def auto_tag(asset_ext, asset_dir=nil) def auto_tag(asset_ext, asset_dir=nil)
if asset_dir.nil? if asset_dir.nil?
asset_dir = case asset_ext asset_dir = case asset_ext
when :js then js_dir when :js
when :css then css_dir js_dir
when :css
css_dir
end end
end end
@ -156,12 +157,18 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
def asset_path(kind, source) def asset_path(kind, source)
return source if source.to_s.include?('//') || source.to_s.start_with?('data:') return source if source.to_s.include?('//') || source.to_s.start_with?('data:')
asset_folder = case kind asset_folder = case kind
when :css then css_dir when :css
when :js then js_dir css_dir
when :images then images_dir when :js
when :fonts then fonts_dir js_dir
else kind.to_s when :images
images_dir
when :fonts
fonts_dir
else
kind.to_s
end end
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}")
@ -177,7 +184,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
# @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?('//') || path.start_with?('data:')
path path
else # rewrite paths to use their destination path else # rewrite paths to use their destination path
if resource = sitemap.find_resource_by_destination_path(url_for(path)) if resource = sitemap.find_resource_by_destination_path(url_for(path))
@ -221,12 +228,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, '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, '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

@ -37,8 +37,8 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
configure_i18n configure_i18n
if !app.build? unless app.build?
logger.info "== Locales: #{langs.join(", ")} (Default #{@mount_at_root})" logger.info "== Locales: #{langs.join(', ')} (Default #{@mount_at_root})"
end end
# Don't output localizable files # Don't output localizable files
@ -70,10 +70,10 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
resources.each do |resource| resources.each do |resource|
# If it uses file extension localization # If it uses file extension localization
if !parse_locale_extension(resource.path).nil? if parse_locale_extension(resource.path)
result = parse_locale_extension(resource.path) result = parse_locale_extension(resource.path)
lang, path, page_id = result ext_lang, path, page_id = result
new_resources << build_resource(path, resource.path, page_id, lang) new_resources << build_resource(path, resource.path, page_id, ext_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))
@ -90,7 +90,6 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
private private
def on_file_changed(file) def on_file_changed(file)
if @locales_regex =~ file if @locales_regex =~ file
@_langs = nil # Clear langs cache @_langs = nil # Clear langs cache
@ -100,7 +99,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 = glob.sub(/\./, '\.').sub(File.join('**', '*'), '.*').sub(/\//, '\/').sub('{rb,yml,yaml}', '(rb|ya?ml)')
%r{^#{regex}} %r{^#{regex}}
end end
@ -124,7 +123,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
lang = @mount_at_root lang = @mount_at_root
end end
instance_vars = Proc.new do instance_vars = proc do
@lang = lang @lang = lang
@page_id = page_id @page_id = page_id
end end
@ -146,8 +145,10 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
Array(options[:langs]).map(&:to_sym) Array(options[:langs]).map(&:to_sym)
else else
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
known_langs.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
@ -178,7 +179,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
::I18n.locale = lang ::I18n.locale = lang
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)

View file

@ -44,7 +44,7 @@ class Middleman::Extensions::AssetHash < ::Middleman::Extension
return if resource.ignored? return if resource.ignored?
# 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]
@ -111,9 +111,7 @@ class Middleman::Extensions::AssetHash < ::Middleman::Extension
end end
end end
end end
end end
end end
# =================Temp Generate Test data============================== # =================Temp Generate Test data==============================

View file

@ -14,7 +14,7 @@ class Middleman::Extensions::AssetHost < ::Middleman::Extension
if asset_host.is_a?(Proc) if asset_host.is_a?(Proc)
config.asset_host(&asset_host) config.asset_host(&asset_host)
else else
config.asset_host do |asset| config.asset_host do |_|
asset_host asset_host
end end
end end

View file

@ -1,6 +1,5 @@
# Automatic Image alt tags from image names extension # Automatic Image alt tags from image names extension
class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
end end
@ -10,14 +9,14 @@ class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
# containing image name. # containing image name.
def image_tag(path) def image_tag(path)
if !path.include?('://') unless 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?('/')
full_path = File.join(source_dir, real_path) full_path = File.join(source_dir, real_path)
if File.exists?(full_path) if File.exist?(full_path)
begin begin
alt_text = File.basename(full_path, '.*') alt_text = File.basename(full_path, '.*')
alt_text.capitalize! alt_text.capitalize!

View file

@ -1,6 +1,5 @@
# Automatic Image Sizes extension # Automatic Image Sizes extension
class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super
@ -16,14 +15,14 @@ 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.key?(:width) && !params.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?('/')
full_path = File.join(source_dir, real_path) full_path = File.join(source_dir, real_path)
if File.exists?(full_path) if File.exist?(full_path)
begin begin
width, height = ::FastImage.size(full_path, :raise_on_failure => true) width, height = ::FastImage.size(full_path, :raise_on_failure => true)
params[:width] = width params[:width] = width
@ -31,7 +30,7 @@ class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
rescue FastImage::UnknownImageType rescue FastImage::UnknownImageType
# No message, it's just not supported # No message, it's just not supported
rescue rescue
warn "Couldn't determine dimensions for image #{path}: #{$!.message}" warn "Couldn't determine dimensions for image #{path}: #{$ERROR_INFO.message}"
end end
end end
end end

View file

@ -1,6 +1,5 @@
# The Cache Buster extension # The Cache Buster extension
class Middleman::Extensions::CacheBuster < ::Middleman::Extension class Middleman::Extensions::CacheBuster < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super

View file

@ -35,7 +35,7 @@ class Middleman::Extensions::Gzip < ::Middleman::Extension
# Farm out gzip tasks to threads and put the results in in_queue # Farm out gzip tasks to threads and put the results in in_queue
out_queue = Queue.new out_queue = Queue.new
threads = num_threads.times.map do num_threads.times.each do
Thread.new do Thread.new do
while path = in_queue.pop while path = in_queue.pop
out_queue << gzip_file(path.to_s) out_queue << gzip_file(path.to_s)

View file

@ -147,7 +147,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
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]
color = options[:color] color = options[:color]
@ -159,7 +159,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
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]
src src
end end

View file

@ -22,7 +22,7 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
class SassCompressor class SassCompressor
def self.compress(style, options={}) def self.compress(style, options={})
root_node = ::Sass::SCSS::CssParser.new(style, 'middleman-css-input', 1).parse root_node = ::Sass::SCSS::CssParser.new(style, 'middleman-css-input', 1).parse
root_node.options = { :style => :compressed } root_node.options = options.merge(:style => :compressed)
root_node.render.strip root_node.render.strip
end end
end end
@ -49,7 +49,7 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
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
$1 << @compressor.compress($2) << $3 $1 << @compressor.compress($2) << $3
end end
@ -66,6 +66,7 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
end end
private private
def inline_html_content?(path) def inline_html_content?(path)
(path.end_with?('.html') || path.end_with?('.php')) && @inline (path.end_with?('.html') || path.end_with?('.php')) && @inline
end end

View file

@ -24,7 +24,6 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
# Rack middleware to look for JS and compress it # Rack middleware to look for JS and compress it
class Rack class Rack
# Init # Init
# @param [Class] app # @param [Class] app
# @param [Hash] options # @param [Hash] options

View file

@ -1,6 +1,5 @@
# Relative Assets extension # Relative Assets extension
class Middleman::Extensions::RelativeAssets < ::Middleman::Extension class Middleman::Extensions::RelativeAssets < ::Middleman::Extension
def initialize(app, options_hash={}, &block) def initialize(app, options_hash={}, &block)
super super

View file

@ -1,6 +1,5 @@
# 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'