This commit is contained in:
Thomas Reynolds 2016-01-14 11:21:42 -08:00
parent 5f8beba4b3
commit d82ac590db
42 changed files with 229 additions and 237 deletions

View file

@ -52,6 +52,8 @@ CaseIndentation:
IndentWhenRelativeTo: end
TrivialAccessors:
ExactNameMatch: true
SingleLineBlockParams:
Enabled: false
Metrics/AbcSize:
Enabled: false
Metrics/PerceivedComplexity:

View file

@ -13,6 +13,8 @@ master
* Don't parse frontmatter on ignored files.
* Fix displaying frontmatter on `/__middleman/sitemap`
* Add `skip_build_clean` config which when set to a block, will avoid removing non-generated paths from build, like .git #1716
* Minor performance improvements
* DRY-up config.rb-specific commands like `ignore` or `path`.
# 4.0.0

View file

@ -3,7 +3,7 @@ require 'rake'
require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__)
ROOT = File.expand_path(File.dirname(__FILE__))
GEM_NAME = 'middleman'
GEM_NAME = 'middleman'.freeze
middleman_gems = %w(middleman-core middleman-cli middleman)
GEM_PATHS = middleman_gems.freeze
@ -36,7 +36,7 @@ end
desc 'Generate documentation for all middleman gems'
task :doc do
GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake yard" }
Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake yard" }
end
end
@ -45,14 +45,14 @@ task :test do
Rake::Task['rubocop'].invoke
GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" }
Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake test" }
end
end
desc 'Run specs for all middleman gems'
task :spec do
GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake spec" }
Dir.chdir(File.join(ROOT, g).to_s) { sh "#{Gem.ruby} -S rake spec" }
end
end

View file

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

View file

@ -52,7 +52,7 @@ module Middleman::Cli
::Middleman::Logger.singleton(verbose, instrument)
::Middleman::Util.instrument "builder_setup" do
::Middleman::Util.instrument 'builder_setup' do
@app = ::Middleman::Application.new do
config[:mode] = :build
config[:environment] = env
@ -67,7 +67,7 @@ module Middleman::Cli
builder.on_build_event(&method(:on_event))
end
::Middleman::Util.instrument "builder_run" do
::Middleman::Util.instrument 'builder_run' do
if builder.run!
clean_directories! if options['clean']
shell.say 'Project built successfully.'

View file

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

View file

@ -170,7 +170,7 @@ module Middleman
ignored = false
file[:relative_path].ascend do |f|
if f.basename.to_s.match %r{^_[^_]}
if f.basename.to_s =~ %r{^_[^_]}
ignored = true
break
end
@ -180,8 +180,7 @@ module Middleman
end,
layout: proc do |file, _sitemap_app|
file[:relative_path].to_s.start_with?('layout.') ||
file[:relative_path].to_s.start_with?('layouts/')
file[:relative_path].to_s.start_with?('layout.', 'layouts/')
end
}, 'Callbacks that can exclude paths from the sitemap'
@ -210,7 +209,7 @@ module Middleman
# Search the root of the project for required files
$LOAD_PATH.unshift(root) unless $LOAD_PATH.include?(root)
::Middleman::Util.instrument "application.setup" do
::Middleman::Util.instrument 'application.setup' do
@callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [
:initialized,
@ -431,6 +430,6 @@ module Middleman
def to_s
"#<Middleman::Application:0x#{object_id}>"
end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
end
end

View file

@ -20,7 +20,7 @@ module Middleman
def_delegator :@app, :logger
# Sort order, images, fonts, js/css and finally everything else.
SORT_ORDER = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .webp .ico .woff .woff2 .otf .ttf .eot .js .css)
SORT_ORDER = %w(.png .jpeg .jpg .gif .bmp .svg .svgz .webp .ico .woff .woff2 .otf .ttf .eot .js .css).freeze
# Create a new Builder instance.
# @param [Middleman::Application] app The app to build.

View file

@ -2,7 +2,7 @@ module Middleman
module CoreExtensions
module Collections
class LazyCollectorStep < BasicObject
DELEGATE = [:hash, :eql?]
DELEGATE = [:hash, :eql?].freeze
def initialize(name, args, block, parent=nil)
@name = name

View file

@ -189,7 +189,7 @@ module Middleman
(@local_data.keys + @local_sources.keys + @callback_sources.keys).include?(key.to_s)
end
alias_method :has_key?, :key?
alias has_key? key?
# Convert all the data into a static hash
#

View file

@ -9,7 +9,7 @@ class Padrino::Helpers::OutputHelpers::ErbHandler
def capture_from_template(*args, &block)
self.output_buffer = ''
buf_was = output_buffer
raw = block.call(*args)
raw = yield(*args)
captured = template.instance_variable_get(:@_out_buf)
self.output_buffer = buf_was
engine_matches?(block) && !captured.empty? ? captured : raw
@ -55,7 +55,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
output.safe_concat ::Padrino::Helpers::TagHelpers::NEWLINE
end
else
output.safe_concat "#{content}"
output.safe_concat content.to_s
end
output.safe_concat "</#{name}>"
@ -66,7 +66,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
result = if handler = auto_find_proper_handler(&block)
handler.capture_from_template(*args, &block)
else
block.call(*args)
yield(*args)
end
::ActiveSupport::SafeBuffer.new.safe_concat(result)

View file

@ -21,7 +21,7 @@ module Middleman
tilde_files: /~$/,
ds_store: /\.DS_Store$/,
git: /(^|\/)\.git(ignore|modules|\/)/
}
}.freeze
# Setup the extension.
def initialize(app, config={}, &block)

View file

@ -127,7 +127,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end
# Backwards API compat
alias_method :langs, :locales
alias langs locales
Contract Symbol
def locale
@ -135,7 +135,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end
# Backwards API compat
alias_method :lang, :locale
alias lang locale
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
@ -274,7 +274,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
File.dirname(path).split('/').each do |path_sub|
next if path_sub == ''
partially_localized_path = "#{partially_localized_path}/#{(::I18n.t("paths.#{path_sub}", default: path_sub).to_s)}"
partially_localized_path = "#{partially_localized_path}/#{::I18n.t("paths.#{path_sub}", default: path_sub)}"
end
path = "#{partially_localized_path}/#{File.basename(path)}"

View file

@ -6,7 +6,6 @@ require 'middleman-core/contracts'
module Middleman
module CoreExtensions
class InlineURLRewriter < ::Middleman::Extension
include Contracts
@ -19,7 +18,7 @@ module Middleman
url_extensions: ArrayOf[String],
source_extensions: ArrayOf[String],
ignore: ArrayOf[IGNORE_DESCRIPTOR]
}
}.freeze
def initialize(app, options_hash={}, &block)
super
@ -33,19 +32,17 @@ module Middleman
end
def after_configuration
app.use Rack, {
rewriters: @rewriters.values,
app.use Rack, rewriters: @rewriters.values,
middleman_app: @app
}
end
class Rack
include Contracts
Contract RespondTo[:call], ({
Contract RespondTo[:call], {
middleman_app: IsA['Middleman::Application'],
rewriters: ArrayOf[REWRITER_DESCRIPTOR]
}) => Any
} => Any
def initialize(app, options={})
@rack_app = app
@middleman_app = options.fetch(:middleman_app)
@ -76,10 +73,8 @@ module Middleman
dirpath = ::Pathname.new(File.dirname(path))
rewritten = nil
# ::Middleman::Util.instrument "inline_url_rewriter", path: path do
rewritten = ::Middleman::Util.rewrite_paths(body, path, all_asset_exts) do |asset_path|
rewritten = ::Middleman::Util.instrument 'inline_url_rewriter', path: path do
::Middleman::Util.rewrite_paths(body, path, all_asset_exts) do |asset_path|
uri = ::Addressable::URI.parse(asset_path)
relative_path = uri.host.nil?
@ -106,7 +101,7 @@ module Middleman
next if ignore.any? { |r| should_ignore?(r, full_asset_path) }
rewrite_ignore = Array(rewriter.fetch(:rewrite_ignore, []))
next if rewrite_ignore.any? { |ignore| ::Middleman::Util.path_match(ignore, path) }
next if rewrite_ignore.any? { |i| ::Middleman::Util.path_match(i, path) }
proc = rewriter.fetch(:proc)
@ -115,7 +110,7 @@ module Middleman
end
asset_path
# end
end
end
::Rack::Response.new(
@ -143,6 +138,5 @@ module Middleman
end
end
end
end
end

View file

@ -496,8 +496,8 @@ module Middleman
@descriptors[k] = []
define_singleton_method(:"__original_#{v}", &method(v))
define_singleton_method(v) do |*args, &block|
@descriptors[k] << method(:"__original_#{v}").call(*args, &block)
define_singleton_method(v) do |*args, &b|
@descriptors[k] << method(:"__original_#{v}").call(*args, &b)
@app.sitemap.rebuild_resource_list!(:"first_run_change_#{v}")
end
end

View file

@ -44,7 +44,7 @@ class Middleman::Extensions::Lorem < ::Middleman::Extension
module LoremObject
class << self
# Words for use in lorem text
WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat)
WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat).freeze
# Get one placeholder word
# @return [String]

View file

@ -36,11 +36,11 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
# Init
# @param [Class] app
# @param [Hash] options
Contract RespondTo[:call], ({
Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER],
inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
}) => Any
} => Any
def initialize(app, options={})
@app = app
@ignore = options.fetch(:ignore)

View file

@ -28,11 +28,11 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
# Init
# @param [Class] app
# @param [Hash] options
Contract RespondTo[:call], ({
Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER],
inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
}) => Any
} => Any
def initialize(app, options={})
@app = app
@ignore = options.fetch(:ignore)

View file

@ -73,11 +73,9 @@ module Middleman
# end
# Render using Tilt
content = nil
# ::Middleman::Util.instrument 'render.tilt', path: path do
content = template.render(context, locs, &block)
# end
content = ::Middleman::Util.instrument 'render.tilt', path: path do
template.render(context, locs, &block)
end
# Allow hooks to manipulate the result after render
content = @app.callbacks_for(:after_render).reduce(content) do |sum, callback|

View file

@ -247,10 +247,10 @@ module Middleman
end
end
if is_logging
http_opts[:Logger] = FilteredWebrickLog.new
http_opts[:Logger] = if is_logging
FilteredWebrickLog.new
else
http_opts[:Logger] = ::WEBrick::Log.new(nil, 0)
::WEBrick::Log.new(nil, 0)
end
begin

View file

@ -10,7 +10,7 @@ module Middleman
true
end
alias_method :to_browser, :to_s
alias to_browser to_s
end
class ServerPlainHostname < SimpleDelegator
@ -24,7 +24,7 @@ module Middleman
# rubocop:enable Style/CaseEquality
end
alias_method :to_browser, :to_s
alias to_browser to_s
end
def self.new(string)

View file

@ -138,7 +138,7 @@ module Middleman
response[1]['Content-Encoding'] = 'gzip' if %w(.svgz .gz).include?(resource.ext)
# Do not set Content-Type if status is 1xx, 204, 205 or 304, otherwise
# Rack will throw an error (500)
if !(100..199).include?(status) && ![204, 205, 304].include?(status)
if !(100..199).cover?(status) && ![204, 205, 304].include?(status)
response[1]['Content-Type'] = resource.content_type || 'application/octet-stream'
end
halt response

View file

@ -35,7 +35,7 @@ module Middleman
def convert_a(el, indent)
content = inner(el, indent)
if el.attr['href'] =~ /\Amailto:/
if el.attr['href'].start_with?('mailto:')
mail_addr = el.attr['href'].sub(/\Amailto:/, '')
href = obfuscate('mailto') << ':' << obfuscate(mail_addr)
content = obfuscate(content) if content == mail_addr

View file

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

View file

@ -8,7 +8,7 @@ module Middleman
# in the wrong direction
ALIASES = {
escape_html: :filter_html
}
}.freeze
def initialize(*args, &block)
super

View file

@ -1,11 +1,9 @@
require 'sass'
module Middleman
module Renderers
# Sass renderer
class Sass < ::Middleman::Extension
opts = { output_style: :nested }
opts[:line_comments] = false if ENV['TEST']
define_setting :sass, opts, 'Sass engine options'

View file

@ -23,9 +23,9 @@ module Middleman
# Ignore based on the source path (without template extensions)
if ignored?(r.path)
r.ignore!
else
elsif !r.is_a?(ProxyResource) && r.file_descriptor && ignored?(r.file_descriptor[:relative_path].to_s)
# This allows files to be ignored by their source file name (with template extensions)
r.ignore! if !r.is_a?(ProxyResource) && r.file_descriptor && ignored?(r.file_descriptor[:relative_path].to_s)
r.ignore!
end
r

View file

@ -113,7 +113,7 @@ module Middleman
def to_s
"#<#{self.class} path=#{@path} target=#{@target}>"
end
alias_method :inspect, :to_s
alias inspect to_s
end
end
end

View file

@ -28,7 +28,7 @@ module Middleman
# Setup a redirect from a path to a target
# @param [String] path
# @param [Hash] opts The :to value gives a target path
Contract String, ({ to: Or[String, ::Middleman::Sitemap::Resource] }), Maybe[Proc] => RedirectDescriptor
Contract String, { to: Or[String, ::Middleman::Sitemap::Resource] }, Maybe[Proc] => RedirectDescriptor
def redirect(path, opts={}, &block)
RedirectDescriptor.new(path, opts[:to], block_given? ? block : nil)
end

View file

@ -44,14 +44,14 @@ module Middleman
def children
return [] unless directory_index?
if eponymous_directory?
base_path = eponymous_directory_path
prefix = %r{^#{base_path.sub("/", "\\/")}}
base_path = if eponymous_directory?
eponymous_directory_path
else
base_path = path.sub("#{@app.config[:index_file]}", '')
prefix = %r{^#{base_path.sub("/", "\\/")}}
path.sub(@app.config[:index_file].to_s, '')
end
prefix = %r{^#{base_path.sub("/", "\\/")}}
@store.resources.select do |sub_resource|
if sub_resource.path == path || sub_resource.path !~ prefix
false

View file

@ -29,9 +29,9 @@ module Middleman
# The path to use when requesting this resource. Normally it's
# the same as {#destination_path} but it can be overridden in subclasses.
# @return [String]
alias_method :request_path, :destination_path
alias request_path destination_path
METADATA_HASH = ({ options: Maybe[Hash], locals: Maybe[Hash], page: Maybe[Hash] })
METADATA_HASH = { options: Maybe[Hash], locals: Maybe[Hash], page: Maybe[Hash] }.freeze
# The metadata for this resource
# @return [Hash]
@ -53,10 +53,10 @@ module Middleman
source = Pathname(source) if source && source.is_a?(String)
if source && source.is_a?(Pathname)
@file_descriptor = ::Middleman::SourceFile.new(source.relative_path_from(@app.source_dir), source, @app.source_dir, Set.new([:source]))
@file_descriptor = if source && source.is_a?(Pathname)
::Middleman::SourceFile.new(source.relative_path_from(@app.source_dir), source, @app.source_dir, Set.new([:source]))
else
@file_descriptor = source
source
end
@destination_path = @path
@ -189,7 +189,7 @@ module Middleman
def to_s
"#<#{self.class} path=#{@path}>"
end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
end
class StringResource < Resource

View file

@ -201,7 +201,7 @@ module Middleman
@lock.synchronize do
return unless @needs_sitemap_rebuild
::Middleman::Util.instrument "sitemap.update", reasons: @rebuild_reasons.uniq do
::Middleman::Util.instrument 'sitemap.update', reasons: @rebuild_reasons.uniq do
@needs_sitemap_rebuild = false
@app.logger.debug '== Rebuilding resource list'
@ -209,7 +209,7 @@ module Middleman
@resources = []
@resource_list_manipulators.each do |m|
::Middleman::Util.instrument "sitemap.manipulator", name: m[:name] do
::Middleman::Util.instrument 'sitemap.manipulator', name: m[:name] do
@app.logger.debug "== Running manipulator: #{m[:name]}"
@resources = m[:manipulator].send(m[:custom_name] || :manipulate_resource_list, @resources)

View file

@ -15,10 +15,10 @@ module Middleman
include Contracts
# Types which could cause output to change.
OUTPUT_TYPES = [:source, :locales, :data]
OUTPUT_TYPES = [:source, :locales, :data].freeze
# Types which require a reload to eval ruby
CODE_TYPES = [:reload]
CODE_TYPES = [:reload].freeze
Matcher = Or[Regexp, RespondTo[:call]]
@ -257,11 +257,11 @@ module Middleman
#
# @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any
def changed(matcher=nil, &block)
def changed(matcher=nil, &_block)
on_change OUTPUT_TYPES do |updated, _removed|
updated
.select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| block.call(f[:relative_path]) }
.each { |f| yield f[:relative_path] }
end
end
@ -269,11 +269,11 @@ module Middleman
#
# @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any
def deleted(matcher=nil, &block)
def deleted(matcher=nil, &_block)
on_change OUTPUT_TYPES do |_updated, removed|
removed
.select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| block.call(f[:relative_path]) }
.each { |f| yield f[:relative_path] }
end
end

View file

@ -202,7 +202,7 @@ module Middleman
def to_s
"#<Middleman::SourceWatcher:0x#{object_id} type=#{@type.inspect} directory=#{@directory.inspect}>"
end
alias_method :inspect, :to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
protected

View file

@ -162,7 +162,7 @@ module Middleman
return nil unless current_path
sitemap.find_resource_by_destination_path(current_path)
end
alias_method :current_page, :current_resource
alias current_page current_resource
protected

View file

@ -28,6 +28,75 @@ module Middleman
@_cache ||= Cache.new
end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
# @param [Symbol] preferred_engine
# @return [String]
Contract IsA['Middleman::Application'], Or[String, Symbol], Symbol => Maybe[IsA['Middleman::SourceFile']]
def self.locate_layout(app, name, preferred_engine=nil)
resolve_opts = {}
resolve_opts[:preferred_engine] = preferred_engine unless preferred_engine.nil?
# Check layouts folder
layout_file = resolve_template(app, File.join(app.config[:layouts_dir], name.to_s), resolve_opts)
# If we didn't find it, check root
layout_file = resolve_template(app, name, resolve_opts) unless layout_file
# Return the path
layout_file
end
# Find a template on disk given a output path
# @param [String] request_path
# @option options [Boolean] :preferred_engine If set, try this engine first, then fall back to any engine.
# @return [String, Boolean] Either the path to the template, or false
Contract IsA['Middleman::Application'], Or[Symbol, String], Maybe[Hash] => Maybe[IsA['Middleman::SourceFile']]
def self.resolve_template(app, request_path, options={})
# Find the path by searching
relative_path = Util.strip_leading_slash(request_path.to_s)
# By default, any engine will do
preferred_engines = []
# If we're specifically looking for a preferred engine
if options.key?(:preferred_engine)
extension_class = ::Tilt[options[:preferred_engine]]
# Get a list of extensions for a preferred engine
preferred_engines += ::Tilt.mappings.select do |_, engines|
engines.include? extension_class
end.keys
end
preferred_engines << '*'
preferred_engines << nil if options[:try_static]
found_template = nil
preferred_engines.each do |preferred_engine|
path_with_ext = relative_path.dup
path_with_ext << ('.' + preferred_engine) unless preferred_engine.nil?
globbing = preferred_engine == '*'
# Cache lookups in build mode only
file = if app.build?
cache.fetch(path_with_ext, preferred_engine) do
app.files.find(:source, path_with_ext, globbing)
end
else
app.files.find(:source, path_with_ext, globbing)
end
found_template = file if file && (preferred_engine.nil? || ::Tilt[file[:full_path]])
break if found_template
end
# If we found one, return it
found_template
end
# Custom error class for handling
class TemplateNotFound < RuntimeError; end
@ -132,16 +201,15 @@ module Middleman
# Look for :layout of any extension
# If found, use it. If not, continue
locate_layout(:layout, layout_engine)
else
elsif layout_file = locate_layout(local_layout, layout_engine)
# Look for specific layout
# If found, use it. If not, error.
if layout_file = locate_layout(local_layout, layout_engine)
layout_file
else
raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate layout: #{local_layout}"
end
end
end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
@ -152,25 +220,6 @@ module Middleman
self.class.locate_layout(@app, name, preferred_engine)
end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
# @param [Symbol] preferred_engine
# @return [String]
Contract IsA['Middleman::Application'], Or[String, Symbol], Symbol => Maybe[IsA['Middleman::SourceFile']]
def self.locate_layout(app, name, preferred_engine=nil)
resolve_opts = {}
resolve_opts[:preferred_engine] = preferred_engine unless preferred_engine.nil?
# Check layouts folder
layout_file = resolve_template(app, File.join(app.config[:layouts_dir], name.to_s), resolve_opts)
# If we didn't find it, check root
layout_file = resolve_template(app, name, resolve_opts) unless layout_file
# Return the path
layout_file
end
# Find a template on disk given a output path
# @param [String] request_path
# @param [Hash] options
@ -179,55 +228,5 @@ module Middleman
def resolve_template(request_path, options={})
self.class.resolve_template(@app, request_path, options)
end
# Find a template on disk given a output path
# @param [String] request_path
# @option options [Boolean] :preferred_engine If set, try this engine first, then fall back to any engine.
# @return [String, Boolean] Either the path to the template, or false
Contract IsA['Middleman::Application'], Or[Symbol, String], Maybe[Hash] => Maybe[IsA['Middleman::SourceFile']]
def self.resolve_template(app, request_path, options={})
# Find the path by searching
relative_path = Util.strip_leading_slash(request_path.to_s)
# By default, any engine will do
preferred_engines = []
# If we're specifically looking for a preferred engine
if options.key?(:preferred_engine)
extension_class = ::Tilt[options[:preferred_engine]]
# Get a list of extensions for a preferred engine
preferred_engines += ::Tilt.mappings.select do |_, engines|
engines.include? extension_class
end.keys
end
preferred_engines << '*'
preferred_engines << nil if options[:try_static]
found_template = nil
preferred_engines.each do |preferred_engine|
path_with_ext = relative_path.dup
path_with_ext << ('.' + preferred_engine) unless preferred_engine.nil?
globbing = preferred_engine == '*'
# Cache lookups in build mode only
file = if app.build?
cache.fetch(path_with_ext, preferred_engine) do
app.files.find(:source, path_with_ext, globbing)
end
else
app.files.find(:source, path_with_ext, globbing)
end
found_template = file if file && (preferred_engine.nil? || ::Tilt[file[:full_path]])
break if found_template
end
# If we found one, return it
found_template
end
end
end

View file

@ -153,7 +153,7 @@ module Middleman
all_files_under(child, &ignore)
end.compact
elsif path.file?
if block_given? && ignore.call(path)
if block_given? && yield(path)
[]
else
[path]
@ -332,7 +332,7 @@ module Middleman
end
Contract String, String, ArrayOf[String], Proc => String
def rewrite_paths(body, _path, exts, &block)
def rewrite_paths(body, _path, exts, &_block)
matcher = /([=\'\"\(,]\s*)([^\s\'\"\)>]+(#{Regexp.union(exts)}))/
url_fn_prefix = 'url('
@ -349,7 +349,7 @@ module Middleman
begin
uri = ::Addressable::URI.parse(asset_path)
if uri.relative? && uri.host.nil? && (result = block.call(asset_path))
if uri.relative? && uri.host.nil? && (result = yield asset_path)
"#{opening_character}#{result}"
else
match

View file

@ -1,5 +1,5 @@
module Middleman
# Current Version
# @return [String]
VERSION = '4.1.0.rc.1' unless const_defined?(:VERSION)
VERSION = '4.1.0.rc.1'.freeze unless const_defined?(:VERSION)
end

View file

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