rubocop 2: the reckoning

This commit is contained in:
Thomas Reynolds 2014-04-29 10:44:24 -07:00
parent 04dc48f13d
commit 8eabe4d354
62 changed files with 328 additions and 363 deletions

View file

@ -25,8 +25,7 @@ Documentation:
Encoding: Encoding:
Enabled: false Enabled: false
HashSyntax: HashSyntax:
# EnforcedStyle: ruby19 EnforcedStyle: ruby19
Enabled: false
SpaceAroundEqualsInParameterDefault: SpaceAroundEqualsInParameterDefault:
EnforcedStyle: no_space EnforcedStyle: no_space
Blocks: Blocks:

28
Gemfile
View file

@ -1,8 +1,8 @@
source 'https://rubygems.org' source 'https://rubygems.org'
# Build and doc tools # Build and doc tools
gem 'rake', '~> 10.0.3', :require => false gem 'rake', '~> 10.0.3', require: false
gem 'yard', '~> 0.8.0', :require => false gem 'yard', '~> 0.8.0', require: false
# Test tools # Test tools
gem 'cucumber', '~> 1.3.1' gem 'cucumber', '~> 1.3.1'
@ -12,17 +12,17 @@ gem 'rspec', '~> 2.12'
gem 'simplecov' gem 'simplecov'
# Optional middleman dependencies, included for tests # Optional middleman dependencies, included for tests
gem 'sinatra', :require => false gem 'sinatra', require: false
gem 'slim', :require => false gem 'slim', require: false
gem 'liquid', :require => false gem 'liquid', require: false
gem 'less', '~> 2.3.0', :require => false gem 'less', '~> 2.3.0', require: false
gem 'stylus', :require => false gem 'stylus', require: false
gem 'asciidoctor', :require => false gem 'asciidoctor', require: false
platforms :ruby do platforms :ruby do
gem 'therubyracer' gem 'therubyracer'
gem 'redcarpet', '~> 3.1' gem 'redcarpet', '~> 3.1'
gem 'pry', :require => false, :group => :development gem 'pry', require: false, group: :development
end end
platforms :jruby do platforms :jruby do
@ -30,10 +30,10 @@ platforms :jruby do
end end
# Code Quality # Code Quality
gem 'coveralls', :require => false gem 'coveralls', require: false
gem 'rubocop', :require => false gem 'rubocop', require: false
# Middleman itself # Middleman itself
gem 'middleman-core', :path => 'middleman-core' gem 'middleman-core', path: 'middleman-core'
gem 'middleman-sprockets', :github => 'middleman/middleman-sprockets' gem 'middleman-sprockets', github: 'middleman/middleman-sprockets'
gem 'middleman', :path => 'middleman' gem 'middleman', path: 'middleman'

View file

@ -1,5 +1,4 @@
require 'rubygems' unless defined?(Gem) require 'rubygems' unless defined?(Gem)
# require 'fileutils' unless defined?(FileUtils)
require 'rake' require 'rake'
require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__) require File.expand_path('../middleman-core/lib/middleman-core/version.rb', __FILE__)
@ -11,7 +10,7 @@ middleman_gems = %w(middleman-core middleman)
GEM_PATHS = middleman_gems.freeze GEM_PATHS = middleman_gems.freeze
def sh_rake(command) def sh_rake(command)
sh "#{Gem.ruby} -S rake #{command}", :verbose => true sh "#{Gem.ruby} -S rake #{command}", verbose: true
end end
desc 'Displays the current version' desc 'Displays the current version'
@ -19,19 +18,6 @@ task :version do
puts "Current version: #{Middleman::VERSION}" puts "Current version: #{Middleman::VERSION}"
end end
desc 'Bumps the version number based on given version'
task :bump, [:version] do |_, args|
raise 'Please specify version=x.x.x !' unless args.version
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}'")
puts "Updating Middleman to version #{args.version}"
File.open(version_path, 'w') { |f| f.write version_text }
sh 'git commit -a -m "Bumped version to %s"' % args.version
end
desc 'Executes a fresh install removing all middleman version and then reinstall all gems'
task :fresh => [:uninstall, :install, :clean]
desc 'Pushes repository to GitHub' desc 'Pushes repository to GitHub'
task :push do task :push do
puts 'Pushing to github...' puts 'Pushing to github...'
@ -41,12 +27,11 @@ task :push do
end end
desc 'Release all middleman gems' desc 'Release all middleman gems'
task :publish => :push do task publish: :push do
puts '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
Rake::Task['clean'].invoke
end end
desc 'Generate documentation for all middleman gems' desc 'Generate documentation for all middleman gems'
@ -61,6 +46,7 @@ task :test do
GEM_PATHS.each do |g| GEM_PATHS.each do |g|
Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" } Dir.chdir("#{File.join(ROOT, g)}") { sh "#{Gem.ruby} -S rake test" }
end end
Rake::Task['rubocop'].invoke
end end
desc 'Run specs for all middleman gems' desc 'Run specs for all middleman gems'
@ -77,4 +63,4 @@ Rubocop::RakeTask.new(:rubocop) do |task|
end end
desc 'Run tests for all middleman gems' desc 'Run tests for all middleman gems'
task :default => :test task default: :test

View file

@ -38,8 +38,8 @@ RSpec::Core::RakeTask.new do |spec|
end end
desc 'Run tests, both RSpec and Cucumber' desc 'Run tests, both RSpec and Cucumber'
task :test => [:spec, :cucumber] task test: [:spec, :cucumber]
YARD::Rake::YardocTask.new YARD::Rake::YardocTask.new
task :default => :test task default: :test

View file

@ -1,4 +1,5 @@
# Setup our load paths # Setup our load paths
# rubocop:disable FileName
libdir = File.expand_path(File.dirname(__FILE__)) libdir = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir) $LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)

View file

@ -52,20 +52,20 @@ module Middleman
class_eval(&block) if block_given? class_eval(&block) if block_given?
include(*extensions) if extensions.any? include(*extensions) if extensions.any?
end end
delegate :helpers, :to => :"self.class" delegate :helpers, to: :"self.class"
# Root project directory (overwritten in middleman build/server) # Root project directory (overwritten in middleman build/server)
# @return [String] # @return [String]
def self.root def self.root
ENV['MM_ROOT'] || Dir.pwd ENV['MM_ROOT'] || Dir.pwd
end end
delegate :root, :to => :"self.class" delegate :root, to: :"self.class"
# Pathname-addressed root # Pathname-addressed root
def self.root_path def self.root_path
Pathname(root) Pathname(root)
end end
delegate :root_path, :to => :"self.class" delegate :root_path, to: :"self.class"
# Name of the source directory # Name of the source directory
# @return [String] # @return [String]
@ -195,7 +195,7 @@ module Middleman
def self.cache def self.cache
@_cache ||= ::Tilt::Cache.new @_cache ||= ::Tilt::Cache.new
end end
delegate :cache, :to => :"self.class" delegate :cache, to: :"self.class"
# Whether we're in development mode # Whether we're in development mode
# @return [Boolean] If we're in dev mode # @return [Boolean] If we're in dev mode
@ -216,7 +216,7 @@ module Middleman
File.join(root, config[:source]) File.join(root, config[:source])
end end
delegate :instrument, :to => ::Middleman::Util delegate :instrument, to: ::Middleman::Util
# Work around this bug: http://bugs.ruby-lang.org/issues/4521 # Work around this bug: http://bugs.ruby-lang.org/issues/4521
# where Ruby will call to_s/inspect while printing exception # where Ruby will call to_s/inspect while printing exception

View file

@ -30,10 +30,11 @@ module Middleman
# @param [Symbol, String, nil] meth # @param [Symbol, String, nil] meth
# @param [Boolean] subcommand # @param [Boolean] subcommand
# @return [void] # @return [void]
# rubocop:disable UnusedMethodArgument
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 => 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|
@ -42,7 +43,7 @@ module Middleman
list.sort! { |a, b| a[0] <=> b[0] } list.sort! { |a, b| a[0] <=> b[0] }
shell.say 'Tasks:' shell.say 'Tasks:'
shell.print_table(list, :ident => 2, :truncate => true) shell.print_table(list, ident: 2, truncate: true)
shell.say shell.say
end end
end end
@ -51,10 +52,7 @@ module Middleman
# @param [Symbol] meth # @param [Symbol] meth
def method_missing(meth, *args) def method_missing(meth, *args)
meth = meth.to_s meth = meth.to_s
meth = self.class.map[meth] if self.class.map.key?(meth)
if self.class.map.key?(meth)
meth = self.class.map[meth]
end
klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}") klass, task = Thor::Util.find_class_and_task_by_namespace("#{meth}:#{meth}")
@ -71,7 +69,7 @@ module Middleman
raise Thor::Error, "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 => shell) klass.start(args, shell: shell)
end end
end end
end end

View file

@ -19,26 +19,26 @@ module Middleman::Cli
desc 'build [options]', 'Builds the static site for deployment' desc 'build [options]', 'Builds the static site for deployment'
method_option :clean, method_option :clean,
:type => :boolean, type: :boolean,
:default => true, default: true,
:desc => 'Remove orphaned files from build (--no-clean to disable)' desc: 'Remove orphaned files from build (--no-clean to disable)'
method_option :glob, method_option :glob,
:type => :string, type: :string,
:aliases => '-g', aliases: '-g',
:default => nil, default: nil,
:desc => 'Build a subset of the project' desc: 'Build a subset of the project'
method_option :verbose, method_option :verbose,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Print debug messages' desc: 'Print debug messages'
method_option :instrument, method_option :instrument,
:type => :string, type: :string,
:default => false, default: false,
:desc => 'Print instrument messages' desc: 'Print instrument messages'
method_option :profile, method_option :profile,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Generate profiling report for the build' desc: 'Generate profiling report for the build'
# Core build Thor command # Core build Thor command
# @return [void] # @return [void]
@ -135,11 +135,11 @@ module Middleman::Cli
# @return [void] # @return [void]
def clean! def clean!
@to_clean.each do |f| @to_clean.each do |f|
base.remove_file f, :force => true base.remove_file f, force: true
end end
Dir[@build_dir.join('**', '*')].select { |d| File.directory?(d) }.each do |d| Dir[@build_dir.join('**', '*')].select { |d| File.directory?(d) }.each do |d|
base.remove_file d, :force => true if directory_empty? d base.remove_file d, force: true if directory_empty? d
end end
end end
@ -273,7 +273,6 @@ module Middleman::Cli
base.say_status :error, file_name, :red base.say_status :error, file_name, :red
if base.debugging if base.debugging
raise e raise e
exit(1)
elsif base.options['verbose'] elsif base.options['verbose']
base.shell.say response, :red base.shell.say response, :red
end end

View file

@ -7,7 +7,7 @@ module Middleman::Cli
namespace :bundle namespace :bundle
desc 'bundle', 'Setup initial bundle', :hide => true desc 'bundle', 'Setup initial bundle', hide: true
# The setup task # The setup task
def bundle def bundle

View file

@ -10,26 +10,24 @@ module Middleman::Cli
desc 'console [options]', 'Start an interactive console in the context of your Middleman application' desc 'console [options]', 'Start an interactive console in the context of your Middleman application'
method_option :environment, method_option :environment,
:aliases => '-e', aliases: '-e',
:default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development', default: ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development',
:desc => 'The environment Middleman will run under' desc: 'The environment Middleman will run under'
method_option :verbose, method_option :verbose,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Print debug messages' desc: 'Print debug messages'
def console def console
require 'middleman-core' require 'middleman-core'
require 'irb' require 'irb'
opts = { opts = {
:environment => options['environment'], environment: options['environment'],
:debug => options['verbose'] debug: options['verbose']
} }
@app = ::Middleman::Application.server.inst do @app = ::Middleman::Application.server.inst do
if opts[:environment] set :environment, opts[:environment].to_sym if opts[:environment]
set :environment, opts[:environment].to_sym
end
::Middleman::Logger.singleton(opts[:debug] ? 0 : 1, opts[:instrumenting] || false) ::Middleman::Logger.singleton(opts[:debug] ? 0 : 1, opts[:instrumenting] || false)
end end

View file

@ -9,7 +9,7 @@ module Middleman::Cli
namespace :extension namespace :extension
# Required path for the new project to be generated # Required path for the new project to be generated
argument :name, :type => :string argument :name, type: :string
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]
@ -33,7 +33,7 @@ module Middleman::Cli
end end
# Output a .gitignore file # Output a .gitignore file
class_option :git, :type => :boolean, :default => true class_option :git, type: :boolean, default: true
no_tasks { no_tasks {
# Write a .gitignore file for project # Write a .gitignore file for project

View file

@ -11,35 +11,35 @@ module Middleman::Cli
desc 'init NAME [options]', 'Create new project NAME' desc 'init NAME [options]', 'Create new project NAME'
available_templates = ::Middleman::Templates.registered.keys.join(', ') available_templates = ::Middleman::Templates.registered.keys.join(', ')
method_option 'template', method_option 'template',
:aliases => '-T', aliases: '-T',
:default => 'default', default: 'default',
:desc => "Use a project template: #{available_templates}" desc: "Use a project template: #{available_templates}"
method_option 'css_dir', method_option 'css_dir',
# :default => "stylesheets", # :default => "stylesheets",
:desc => 'The path to the css files' desc: 'The path to the css files'
method_option 'js_dir', method_option 'js_dir',
# :default => "javascripts", # :default => "javascripts",
:desc => 'The path to the javascript files' desc: 'The path to the javascript files'
method_option 'images_dir', method_option 'images_dir',
# :default => "images", # :default => "images",
:desc => 'The path to the image files' desc: 'The path to the image files'
method_option 'rack', method_option 'rack',
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Include a config.ru file' desc: 'Include a config.ru file'
method_option 'skip-gemfile', method_option 'skip-gemfile',
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => "Don't create a Gemfile" desc: "Don't create a Gemfile"
method_option 'skip-bundle', method_option 'skip-bundle',
:type => :boolean, type: :boolean,
:aliases => '-B', aliases: '-B',
:default => false, default: false,
:desc => "Don't run bundle install" desc: "Don't run bundle install"
method_option 'skip-git', method_option 'skip-git',
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Skip Git ignores and keeps' desc: 'Skip Git ignores and keeps'
# The init task # The init task
# @param [String] name # @param [String] name
def init(name='.') def init(name='.')

View file

@ -8,47 +8,47 @@ module Middleman::Cli
desc 'server [options]', 'Start the preview server' desc 'server [options]', 'Start the preview server'
method_option :environment, method_option :environment,
:aliases => '-e', aliases: '-e',
:default => ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development', default: ENV['MM_ENV'] || ENV['RACK_ENV'] || 'development',
:desc => 'The environment Middleman will run under' desc: 'The environment Middleman will run under'
method_option :host, method_option :host,
:type => :string, type: :string,
:aliases => '-h', aliases: '-h',
:default => '0.0.0.0', default: '0.0.0.0',
:desc => 'Bind to HOST address' desc: 'Bind to HOST address'
method_option :port, method_option :port,
:aliases => '-p', aliases: '-p',
:default => '4567', default: '4567',
:desc => 'The port Middleman will listen on' desc: 'The port Middleman will listen on'
method_option :verbose, method_option :verbose,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Print debug messages' desc: 'Print debug messages'
method_option :instrument, method_option :instrument,
:type => :string, type: :string,
:default => false, default: false,
:desc => 'Print instrument messages' desc: 'Print instrument messages'
method_option :disable_watcher, method_option :disable_watcher,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Disable the file change and delete watcher process' desc: 'Disable the file change and delete watcher process'
method_option :profile, method_option :profile,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Generate profiling report for server startup' desc: 'Generate profiling report for server startup'
method_option :reload_paths, method_option :reload_paths,
:type => :string, type: :string,
:default => false, default: false,
:desc => 'Additional paths to auto-reload when files change' desc: 'Additional paths to auto-reload when files change'
method_option :force_polling, method_option :force_polling,
:type => :boolean, type: :boolean,
:default => false, default: false,
:desc => 'Force file watcher into polling mode' desc: 'Force file watcher into polling mode'
method_option :latency, method_option :latency,
:type => :numeric, type: :numeric,
:aliases => '-l', aliases: '-l',
:default => 0.25, default: 0.25,
:desc => 'Set file watcher latency, in seconds' desc: 'Set file watcher latency, in seconds'
# Start the server # Start the server
def server def server
@ -63,15 +63,15 @@ module Middleman::Cli
end end
params = { params = {
:port => options['port'], port: options['port'],
:host => options['host'], host: options['host'],
:environment => options['environment'], environment: options['environment'],
:debug => options['verbose'], debug: options['verbose'],
:instrumenting => options['instrument'], instrumenting: options['instrument'],
:disable_watcher => options['disable_watcher'], disable_watcher: options['disable_watcher'],
:reload_paths => options['reload_paths'], reload_paths: options['reload_paths'],
:force_polling => options['force_polling'], force_polling: options['force_polling'],
:latency => options['latency'] latency: options['latency']
} }
puts '== The Middleman is loading' puts '== The Middleman is loading'

View file

@ -111,16 +111,17 @@ module Middleman
# Get the value of a setting by key. Returns nil if there is no such setting. # Get the value of a setting by key. Returns nil if there is no such setting.
# @return [Object] # @return [Object]
def [](key) def [](key)
setting = @settings[key] setting_obj = setting(key)
setting ? setting.value : nil setting_obj ? setting_obj.value : nil
end end
# Set the value of a setting by key. Creates the setting if it doesn't exist. # Set the value of a setting by key. Creates the setting if it doesn't exist.
# @param [Symbol] key # @param [Symbol] key
# @param [Object] val # @param [Object] val
# rubocop:disable UselessSetterCall
def []=(key, val) def []=(key, val)
setting = @settings[key] || define_setting(key) setting_obj = setting(key) || define_setting(key)
setting.value = val setting_obj.value = val
end end
# Allow configuration settings to be read and written via methods # Allow configuration settings to be read and written via methods
@ -227,6 +228,7 @@ module Middleman
end end
# Whether or not there has been a value set beyond the default # Whether or not there has been a value set beyond the default
# rubocop:disable TrivialAccessors
def value_set? def value_set?
@value_set @value_set
end end

View file

@ -143,9 +143,6 @@ module Middleman
def data_for_path(path) def data_for_path(path)
response = nil response = nil
@@local_sources ||= {}
@@callback_sources ||= {}
if store.key?(path.to_s) if store.key?(path.to_s)
response = store[path.to_s] response = store[path.to_s]
elsif callbacks.key?(path.to_s) elsif callbacks.key?(path.to_s)
@ -164,10 +161,7 @@ module Middleman
return @local_data[path.to_s] return @local_data[path.to_s]
else else
result = data_for_path(path) result = data_for_path(path)
return ::Middleman::Util.recursively_enhance(result) if result
if result
return ::Middleman::Util.recursively_enhance(result)
end
end end
super super
@ -187,11 +181,11 @@ module Middleman
__send__(key) if key?(key) __send__(key) if key?(key)
end end
def has_key?(key) def key?(key)
@local_data.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? alias_method :has_key?, :key?
# Convert all the data into a static hash # Convert all the data into a static hash
# #

View file

@ -48,7 +48,7 @@ module Middleman
app.extend ClassMethods app.extend ClassMethods
app.send :include, InstanceMethods app.send :include, InstanceMethods
app.delegate :configure, :to => :"self.class" app.delegate :configure, to: :"self.class"
end end
alias_method :included, :registered alias_method :included, :registered
end end
@ -95,6 +95,7 @@ module Middleman
# #
# @param [Symbol, Module] ext Which extension to activate # @param [Symbol, Module] ext Which extension to activate
# @return [void] # @return [void]
# rubocop:disable BlockNesting
def activate(ext, options={}, &block) def activate(ext, options={}, &block)
ext_module = if ext.is_a?(Module) ext_module = if ext.is_a?(Module)
ext ext

View file

@ -61,7 +61,7 @@ module Middleman
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
# Initialize api and internal path cache # Initialize api and internal path cache
def initialize(app) def initialize(app)

View file

@ -43,7 +43,7 @@ module Middleman::CoreExtensions
data[opt] = fmdata[opt] unless fmdata[opt].nil? data[opt] = fmdata[opt] unless fmdata[opt].nil?
end end
{ :options => data, :page => ::Middleman::Util.recursively_enhance(fmdata).freeze } { options: data, page: ::Middleman::Util.recursively_enhance(fmdata).freeze }
end end
end end
@ -114,6 +114,7 @@ module Middleman::CoreExtensions
end end
private private
# Parse YAML frontmatter out of a string # Parse YAML frontmatter out of a string
# @param [String] content # @param [String] content
# @return [Array<Hash, String>] # @return [Array<Hash, String>]

View file

@ -1,12 +1,12 @@
# Shutup Tilt Warnings # Shutup Tilt Warnings
# @private # @private
class Tilt::Template class Tilt::Template
def warn(*args) def warn(*)
# Kernel.warn(*args)
end end
end end
# Rendering extension # Rendering extension
# rubocop:disable UnderscorePrefixedVariableName
module Middleman module Middleman
module CoreExtensions module CoreExtensions
module Rendering module Rendering
@ -402,6 +402,7 @@ module Middleman
end end
# The currently rendering engine # The currently rendering engine
# rubocop:disable TrivialAccessors
# @return [Symbol, nil] # @return [Symbol, nil]
def current_engine=(v) def current_engine=(v)
@_current_engine = v @_current_engine = v
@ -427,7 +428,7 @@ module Middleman
extension_class = ::Tilt[options[:preferred_engine]] extension_class = ::Tilt[options[:preferred_engine]]
# 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 |_, engines|
engines.include? extension_class engines.include? extension_class
end.keys end.keys

View file

@ -69,15 +69,15 @@ module Middleman
app.use Rack::Lint app.use Rack::Lint
app.use Rack::Head app.use Rack::Head
Array(@middleware).each do |klass, options, block| Array(@middleware).each do |klass, options, middleware_block|
app.use(klass, *options, &block) app.use(klass, *options, &middleware_block)
end end
inner_app = inst(&block) inner_app = inst(&block)
app.map('/') { run inner_app } app.map('/') { run inner_app }
Array(@mappings).each do |path, block| Array(@mappings).each do |path, map_block|
app.map(path, &block) app.map(path, &map_block)
end end
app app
@ -125,6 +125,7 @@ module Middleman
# configuration can be included later without impacting # configuration can be included later without impacting
# other classes and instances. # other classes and instances.
# #
# rubocop:disable ClassVars
# @return [Class] # @return [Class]
def server(&block) def server(&block)
@@servercounter ||= 0 @@servercounter ||= 0
@ -165,13 +166,13 @@ module Middleman
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"
delegate :map, :to => :"self.class" delegate :map, to: :"self.class"
# Rack request # Rack request
# @return [Rack::Request] # @return [Rack::Request]

View file

@ -39,7 +39,7 @@ module Middleman
# Use the metadata loop for matching against paths at runtime # Use the metadata loop for matching against paths at runtime
sitemap.provides_metadata_for_path(url) do |_| sitemap.provides_metadata_for_path(url) do |_|
{ :options => opts, :blocks => blocks } { options: opts, blocks: blocks }
end end
return return
@ -54,7 +54,8 @@ module Middleman
# Setup proxy # Setup proxy
if target = opts.delete(:proxy) if target = opts.delete(:proxy)
# TODO: deprecate proxy through page? # TODO: deprecate proxy through page?
proxy(url, target, opts, &block) and return proxy(url, target, opts, &block)
return
elsif opts.delete(:ignore) elsif opts.delete(:ignore)
# TODO: deprecate ignore through page? # TODO: deprecate ignore through page?
ignore(url) ignore(url)
@ -62,7 +63,7 @@ module Middleman
# Setup a metadata matcher for rendering those options # Setup a metadata matcher for rendering those options
sitemap.provides_metadata_for_path(url) do |_| sitemap.provides_metadata_for_path(url) do |_|
{ :options => opts, :blocks => blocks } { options: opts, blocks: blocks }
end end
end end
end end

View file

@ -16,9 +16,7 @@ module Middleman
# When in dev # When in dev
app.configure :development do app.configure :development do
# Include middlemare # Include middlemare
if config[:show_exceptions] use ::Rack::ShowExceptions if config[:show_exceptions]
use ::Rack::ShowExceptions
end
end end
end end
end end

View file

@ -3,9 +3,9 @@ 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
class_attribute :ext_name, :instance_reader => false, :instance_writer => false class_attribute :ext_name, instance_reader: false, instance_writer: false
class << self class << self
def config def config
@ -23,7 +23,7 @@ module Middleman
def helpers(*m, &block) def helpers(*m, &block)
self.defined_helpers ||= [] self.defined_helpers ||= []
if block if block_given?
mod = Module.new mod = Module.new
mod.module_eval(&block) mod.module_eval(&block)
m = [mod] m = [mod]
@ -66,7 +66,7 @@ module Middleman
attr_accessor :options attr_accessor :options
attr_reader :app attr_reader :app
delegate :after_extension_activated, :to => :"::Middleman::Extension" delegate :after_extension_activated, to: :"::Middleman::Extension"
def initialize(klass, options_hash={}, &block) def initialize(klass, options_hash={}, &block)
@_helpers = [] @_helpers = []
@ -92,7 +92,7 @@ module Middleman
protected protected
def setup_options(options_hash, &block) def setup_options(options_hash)
@options = self.class.config.dup @options = self.class.config.dup
@options.finalize! @options.finalize!
@ -127,10 +127,9 @@ module Middleman
def bind_after_configuration def bind_after_configuration
ext = self ext = self
@klass.after_configuration do @klass.after_configuration do
if ext.respond_to?(:after_configuration) ext.after_configuration if ext.respond_to?(:after_configuration)
ext.after_configuration
end
# rubocop:disable IfUnlessModifier
if ext.respond_to?(:manipulate_resource_list) if ext.respond_to?(:manipulate_resource_list)
ext.app.sitemap.register_resource_list_manipulator(ext.class.extension_name, ext) ext.app.sitemap.register_resource_list_manipulator(ext.class.extension_name, ext)
end end

View file

@ -19,7 +19,7 @@ module Middleman
meta_pages = self meta_pages = self
@rack_app = Rack::Builder.new do @rack_app = Rack::Builder.new do
# Serve assets from metadata/assets # Serve assets from metadata/assets
use Rack::Static, :urls => ['/assets'], :root => File.join(File.dirname(__FILE__), 'meta_pages') use Rack::Static, urls: ['/assets'], root: File.join(File.dirname(__FILE__), 'meta_pages')
map '/' do map '/' do
run meta_pages.method(:index) run meta_pages.method(:index)
@ -54,7 +54,7 @@ module Middleman
sitemap_tree.add_resource resource sitemap_tree.add_resource resource
end end
template('sitemap.html.erb', :sitemap_tree => sitemap_tree) template('sitemap.html.erb', sitemap_tree: sitemap_tree)
end end
# Inspect configuration # Inspect configuration
@ -80,9 +80,9 @@ module Middleman
end end
template('config.html.erb', template('config.html.erb',
:global_config => global_config, global_config: global_config,
:extension_config => extension_config, extension_config: extension_config,
:registered_extensions => Middleman::Extensions.registered.dup) registered_extensions: Middleman::Extensions.registered.dup)
end end
private private

View file

@ -15,17 +15,17 @@ module Middleman
content = '' content = ''
key_classes = ['key'] key_classes = ['key']
key_classes << 'modified' if @setting.value_set? key_classes << 'modified' if @setting.value_set?
content << content_tag(:span, @setting.key.pretty_inspect.strip, :class => key_classes.join(' ')) content << content_tag(:span, @setting.key.pretty_inspect.strip, class: key_classes.join(' '))
content << ' = ' content << ' = '
content << content_tag(:span, @setting.value.pretty_inspect.strip, :class => 'value') content << content_tag(:span, @setting.value.pretty_inspect.strip, class: 'value')
if @setting.default && @setting.value_set? && @setting.default != @setting.value if @setting.default && @setting.value_set? && @setting.default != @setting.value
content << content_tag(:span, :class => 'default') do content << content_tag(:span, class: 'default') do
"(Default: #{@setting.default.inspect})" "(Default: #{@setting.default.inspect})"
end end
end end
if @setting.description if @setting.description
content << content_tag(:p, :class => 'description') do content << content_tag(:p, class: 'description') do
@setting.description @setting.description
end end
end end

View file

@ -14,7 +14,7 @@ module Middleman
def render def render
classes = 'resource-details' classes = 'resource-details'
classes << ' ignored' if @resource.ignored? classes << ' ignored' if @resource.ignored?
content_tag :div, :class => classes do content_tag :div, class: classes do
content_tag :table do content_tag :table do
content = '' content = ''
resource_properties.each do |label, value| resource_properties.each do |label, value|
@ -38,7 +38,7 @@ module Middleman
build_path = @resource.destination_path build_path = @resource.destination_path
build_path = 'Not built' if ignored? build_path = 'Not built' if ignored?
props['Build Path'] = build_path if @resource.path != build_path props['Build Path'] = build_path if @resource.path != build_path
props['URL'] = content_tag(:a, @resource.url, :href => @resource.url) unless ignored? props['URL'] = content_tag(:a, @resource.url, href: @resource.url) unless ignored?
props['Source File'] = @resource.source_file.sub(/^#{Regexp.escape(ENV['MM_ROOT'] + '/')}/, '') props['Source File'] = @resource.source_file.sub(/^#{Regexp.escape(ENV['MM_ROOT'] + '/')}/, '')
data = @resource.data data = @resource.data

View file

@ -13,8 +13,7 @@ module Middleman
end end
def render def render
content = '' sorted_children_keys = @children.keys.sort do |a, b|
@children.keys.sort do |a, b|
a_subtree = @children[a] a_subtree = @children[a]
b_subtree = @children[b] b_subtree = @children[b]
if a_subtree.is_a? SitemapResource if a_subtree.is_a? SitemapResource
@ -32,7 +31,9 @@ module Middleman
else else
a.downcase <=> b.downcase a.downcase <=> b.downcase
end end
end.each do |path_part| end
sorted_children_keys.reduce('') do |content, path_part|
subtree = @children[path_part] subtree = @children[path_part]
content << "<details class='#{subtree.css_classes.join(' ')}'>" content << "<details class='#{subtree.css_classes.join(' ')}'>"
content << '<summary>' content << '<summary>'
@ -41,7 +42,6 @@ module Middleman
content << subtree.render content << subtree.render
content << '</details>' content << '</details>'
end end
content
end end
def css_classes def css_classes

View file

@ -2,13 +2,14 @@ require 'webrick'
require 'middleman-core/meta_pages' require 'middleman-core/meta_pages'
require 'middleman-core/logger' require 'middleman-core/logger'
# rubocop:disable GlobalVars
module Middleman module Middleman
module PreviewServer module PreviewServer
DEFAULT_PORT = 4567 DEFAULT_PORT = 4567
class << self class << self
attr_reader :app, :host, :port attr_reader :app, :host, :port
delegate :logger, :to => :app delegate :logger, to: :app
# Start an instance of Middleman::Application # Start an instance of Middleman::Application
# @return [void] # @return [void]
@ -89,6 +90,7 @@ module Middleman
end end
private private
def new_app def new_app
opts = @options.dup opts = @options.dup
server = ::Middleman::Application.server server = ::Middleman::Application.server
@ -119,7 +121,7 @@ module Middleman
if first_run if first_run
# Watcher Library # Watcher Library
require 'listen' require 'listen'
@listener = Listen.to(Dir.pwd, :relative_paths => true, :force_polling => @options[:force_polling]) @listener = Listen.to(Dir.pwd, relative_paths: true, force_polling: @options[:force_polling])
@listener.latency(@options[:latency]) @listener.latency(@options[:latency])
end end
@ -165,10 +167,10 @@ module Middleman
# @return [void] # @return [void]
def setup_webrick(is_logging) def setup_webrick(is_logging)
http_opts = { http_opts = {
:BindAddress => host, BindAddress: host,
:Port => port, Port: port,
:AccessLog => [], AccessLog: [],
:DoNotReverseLookup => true DoNotReverseLookup: true
} }
if is_logging if is_logging

View file

@ -1,6 +1,7 @@
module Middleman module Middleman
module Profiling module Profiling
# The profiler instance. There can only be one! # The profiler instance. There can only be one!
# rubocop:disable TrivialAccessors
def self.profiler=(prof) def self.profiler=(prof)
@profiler = prof @profiler = prof
end end
@ -23,7 +24,7 @@ module Middleman
def start def start
end end
def report(report_name) def report(_)
end end
end end
@ -47,7 +48,7 @@ module Middleman
outfile = (outfile + '.html') unless outfile.end_with? '.html' outfile = (outfile + '.html') unless outfile.end_with? '.html'
FileUtils.mkdir_p(File.dirname(outfile)) FileUtils.mkdir_p(File.dirname(outfile))
File.open(outfile, 'w') do |f| File.open(outfile, 'w') do |f|
printer.print(f, :min_percent => 1) printer.print(f, min_percent: 1)
end end
end end
end end

View file

@ -6,13 +6,13 @@ module Middleman
class << self class << self
def registered(app) def registered(app)
app.config.define_setting :asciidoc, { app.config.define_setting :asciidoc, {
:safe => :safe, safe: :safe,
:backend => :html5, backend: :html5,
:attributes => %W(showtitle env=middleman env-middleman middleman-version=#{::Middleman::VERSION}) attributes: %W(showtitle env=middleman env-middleman middleman-version=#{::Middleman::VERSION})
}, 'AsciiDoc engine options (Hash)' }, 'AsciiDoc engine options (Hash)'
app.config.define_setting :asciidoc_attributes, [], 'AsciiDoc custom attributes (Array)' app.config.define_setting :asciidoc_attributes, [], 'AsciiDoc custom attributes (Array)'
app.before_configuration do app.before_configuration do
template_extensions :adoc => :html template_extensions adoc: :html
end end
app.after_configuration do app.after_configuration do
@ -23,7 +23,7 @@ module Middleman
sitemap.provides_metadata(/\.adoc$/) do |path| sitemap.provides_metadata(/\.adoc$/) do |path|
# read the AsciiDoc header only to set page options and data # read the AsciiDoc header only to set page options and data
# header values can be accessed via app.data.page.<name> in the layout # header values can be accessed via app.data.page.<name> in the layout
doc = Asciidoctor.load_file path, :safe => :safe, :parse_header_only => true doc = Asciidoctor.load_file path, safe: :safe, parse_header_only: true
opts = {} opts = {}
if doc.attr? 'page-layout' if doc.attr? 'page-layout'
@ -35,7 +35,7 @@ module Middleman
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
# opts[:attributes].concat %W(docfile=#{path} docdir=#{File.dirname path} docname=#{(File.basename path).sub(/\.adoc$/, '')}) # opts[:attributes].concat %W(docfile=#{path} docdir=#{File.dirname path} docname=#{(File.basename path).sub(/\.adoc$/, '')})
@ -43,10 +43,10 @@ module Middleman
page = {} page = {}
page[:title] = doc.doctitle page[:title] = doc.doctitle
page[:date] = (doc.attr 'date') unless (doc.attr 'date').nil? page[:date] = (doc.attr 'date') unless (doc.attr 'date').nil?
# TODO grab all the author information # TODO: grab all the author information
page[:author] = (doc.attr 'author') unless (doc.attr 'author').nil? page[:author] = (doc.attr 'author') unless (doc.attr 'author').nil?
{ :options => opts, :page => ::Middleman::Util.recursively_enhance(page) } { options: opts, page: ::Middleman::Util.recursively_enhance(page) }
end end
end end
end end

View file

@ -14,7 +14,7 @@ module Middleman
::Tilt.prefer(DebuggingCoffeeScriptTemplate) ::Tilt.prefer(DebuggingCoffeeScriptTemplate)
app.before_configuration do app.before_configuration do
template_extensions :coffee => :js template_extensions coffee: :js
DebuggingCoffeeScriptTemplate.middleman_app = self DebuggingCoffeeScriptTemplate.middleman_app = self
end end
end end

View file

@ -7,7 +7,7 @@ module Middleman
# once registered # once registered
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
template_extensions :erb => :html template_extensions erb: :html
end end
# After config # After config

View file

@ -20,7 +20,7 @@ module Middleman
# Once registered # Once registered
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
template_extensions :haml => :html template_extensions haml: :html
end end
# Add haml helpers to context # Add haml helpers to context

View file

@ -4,7 +4,7 @@ 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(*)
@output ||= begin @output ||= begin
output, warnings = MiddlemanKramdownHTML.convert(@engine.root, @engine.options) output, warnings = MiddlemanKramdownHTML.convert(@engine.root, @engine.options)
@engine.warnings.concat(warnings) @engine.warnings.concat(warnings)
@ -17,7 +17,7 @@ module Middleman
class MiddlemanKramdownHTML < ::Kramdown::Converter::Html class MiddlemanKramdownHTML < ::Kramdown::Converter::Html
cattr_accessor :middleman_app cattr_accessor :middleman_app
def convert_img(el, indent) def convert_img(el, _)
attrs = el.attr.dup attrs = el.attr.dup
link = attrs.delete('src') link = attrs.delete('src')

View file

@ -12,7 +12,7 @@ module Middleman
app.config.define_setting :less, {}, 'LESS compiler options' app.config.define_setting :less, {}, 'LESS compiler options'
app.before_configuration do app.before_configuration do
template_extensions :less => :css template_extensions less: :css
end end
app.after_configuration do app.after_configuration do
@ -33,7 +33,7 @@ module Middleman
if ::Less.const_defined? :Engine if ::Less.const_defined? :Engine
@engine = ::Less::Engine.new(data) @engine = ::Less::Engine.new(data)
else else
parser = ::Less::Parser.new(options.merge :filename => eval_file, :line => line, :paths => ['.', File.dirname(eval_file)]) parser = ::Less::Parser.new(options.merge filename: eval_file, line: line, paths: ['.', File.dirname(eval_file)])
@engine = parser.parse(data) @engine = parser.parse(data)
end end
end end

View file

@ -10,7 +10,7 @@ module Middleman
# Once registerd # Once registerd
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
template_extensions :liquid => :html template_extensions liquid: :html
end end
# After config, setup liquid partial paths # After config, setup liquid partial paths
@ -18,8 +18,8 @@ module Middleman
::Liquid::Template.file_system = ::Liquid::LocalFileSystem.new(source_dir) ::Liquid::Template.file_system = ::Liquid::LocalFileSystem.new(source_dir)
# Convert data object into a hash for liquid # Convert data object into a hash for liquid
sitemap.provides_metadata %r{\.liquid$} do |path| sitemap.provides_metadata %r{\.liquid$} do
{ :locals => { :data => data.to_h } } { locals: { data: data.to_h } }
end end
end end
end end

View file

@ -11,11 +11,11 @@ module Middleman
app.config.define_setting :markdown_engine_prefix, ::Tilt, 'The parent module for markdown template engines' app.config.define_setting :markdown_engine_prefix, ::Tilt, 'The parent module for markdown template engines'
app.before_configuration do app.before_configuration do
template_extensions :markdown => :html, template_extensions markdown: :html,
:mdown => :html, mdown: :html,
:md => :html, md: :html,
:mkd => :html, mkd: :html,
:mkdn => :html mkdn: :html
end end
# Once configuration is parsed # Once configuration is parsed

View file

@ -6,7 +6,7 @@ module Middleman
# because tilt has decided to convert these # because tilt has decided to convert these
# in the wrong direction # in the wrong direction
ALIASES = { ALIASES = {
:escape_html => :filter_html escape_html: :filter_html
} }
# Overwrite built-in Tilt version. # Overwrite built-in Tilt version.
@ -59,7 +59,7 @@ module Middleman
def image(link, title, alt_text) def image(link, title, alt_text)
if !@local_options[:no_images] if !@local_options[:no_images]
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
@ -69,7 +69,7 @@ module Middleman
def link(link, title, content) def link(link, title, content)
if !@local_options[:no_links] if !@local_options[:no_links]
attributes = { :title => title } attributes = { title: title }
attributes.merge!(@local_options[:link_attributes]) if @local_options[:link_attributes] attributes.merge!(@local_options[:link_attributes]) if @local_options[:link_attributes]
middleman_app.link_to(content, link, attributes) middleman_app.link_to(content, link, attributes)

View file

@ -13,8 +13,8 @@ module Middleman
app.config.define_setting :sass, {}, 'Sass engine options' app.config.define_setting :sass, {}, 'Sass engine options'
app.before_configuration do app.before_configuration do
template_extensions :scss => :css, template_extensions scss: :css,
:sass => :css sass: :css
end end
# Tell Tilt to use it as well (for inline sass blocks) # Tell Tilt to use it as well (for inline sass blocks)
@ -36,9 +36,7 @@ module Middleman
def initialize(*args, &block) def initialize(*args, &block)
super super
if @options.key?(:context) @context = @options[:context] if @options.key?(:context)
@context = @options[:context]
end
end end
# Define the expected syntax for the template # Define the expected syntax for the template
@ -51,23 +49,22 @@ module Middleman
# Add exception messaging # Add exception messaging
# @param [Class] context # @param [Class] context
# @param [Hash] locals
# @return [String] # @return [String]
def evaluate(context, locals, &block) def evaluate(context, _)
@context ||= context @context ||= context
@engine = ::Sass::Engine.new(data, sass_options) @engine = ::Sass::Engine.new(data, sass_options)
begin begin
@engine.render @engine.render
rescue ::Sass::SyntaxError => e rescue ::Sass::SyntaxError => e
::Sass::SyntaxError.exception_to_css(e, :full_exception => true) ::Sass::SyntaxError.exception_to_css(e, full_exception: true)
end end
end end
# Change Sass path, for url functions, to the build folder if we're building # Change Sass path, for url functions, to the build folder if we're building
# @return [Hash] # @return [Hash]
def sass_options def sass_options
more_opts = { :filename => eval_file, :line => line, :syntax => syntax } more_opts = { filename: eval_file, line: line, syntax: syntax }
if @context.is_a?(::Middleman::Application) && file if @context.is_a?(::Middleman::Application) && file
location_of_sass_file = @context.source_dir location_of_sass_file = @context.source_dir

View file

@ -24,20 +24,20 @@ module Middleman
# Once registered # Once registered
def registered(app) def registered(app)
app.before_configuration do app.before_configuration do
template_extensions :slim => :html template_extensions slim: :html
end end
# Setup Slim options to work with partials # Setup Slim options to work with partials
::Slim::Engine.set_default_options( ::Slim::Engine.set_default_options(
:buffer => '@_out_buf', buffer: '@_out_buf',
:use_html_safe => true, use_html_safe: true,
:generator => ::Temple::Generators::RailsOutputBuffer, generator: ::Temple::Generators::RailsOutputBuffer,
:disable_escape => true disable_escape: true
) )
app.after_configuration do app.after_configuration do
context_hack = { context_hack = {
:context => self context: self
} }
::Slim::Embedded::SassEngine.disable_option_validator! ::Slim::Embedded::SassEngine.disable_option_validator!

View file

@ -13,7 +13,7 @@ module Middleman
app.set :styl, {} app.set :styl, {}
app.before_configuration do app.before_configuration do
template_extensions :styl => :css template_extensions styl: :css
end end
end end

View file

@ -25,17 +25,17 @@ module Middleman
# Setup callbacks which can exclude paths from the sitemap # Setup callbacks which can exclude paths from the sitemap
app.config.define_setting :ignored_sitemap_matchers, { app.config.define_setting :ignored_sitemap_matchers, {
# dotfiles and folders in the root # dotfiles and folders in the root
:root_dotfiles => proc { |file| file.start_with?('.') }, root_dotfiles: proc { |file| file.start_with?('.') },
# Files starting with an dot, but not .htaccess # Files starting with an dot, but not .htaccess
:source_dotfiles => proc { |file| source_dotfiles: proc { |file|
file =~ %r{/\.} && file !~ %r{/\.(htaccess|htpasswd|nojekyll)} file =~ %r{/\.} && file !~ %r{/\.(htaccess|htpasswd|nojekyll)}
}, },
# 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, sitemap_app| layout: proc { |file, sitemap_app|
file.start_with?(File.join(sitemap_app.config[:source], 'layout.')) || file.start_with?(File.join(sitemap_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'

View file

@ -35,13 +35,13 @@ module Middleman
# Update or add an on-disk file path # Update or add an on-disk file path
# @param [String] file # @param [String] file
# @return [Boolean] # @return [Boolean]
def touch_file(file, rebuild=true) def touch_file(file)
return false if File.directory?(file) return false if File.directory?(file)
path = @sitemap.file_to_path(file) path = @sitemap.file_to_path(file)
return false unless path return false unless path
ignored = @app.config[:ignored_sitemap_matchers].any? do |name, callback| ignored = @app.config[:ignored_sitemap_matchers].any? do |_, callback|
if callback.arity == 1 if callback.arity == 1
callback.call(file) callback.call(file)
else else
@ -67,7 +67,7 @@ module Middleman
# Remove a file from the store # Remove a file from the store
# @param [String] file # @param [String] file
# @return [void] # @return [void]
def remove_file(file, rebuild=true) def remove_file(file)
if @file_paths_on_disk.delete?(file) if @file_paths_on_disk.delete?(file)
@sitemap.rebuild_resource_list!(:removed_file) @sitemap.rebuild_resource_list!(:removed_file)
unless waiting_for_ready || @app.build? unless waiting_for_ready || @app.build?

View file

@ -17,9 +17,10 @@ module Middleman
module ResourceInstanceMethods module ResourceInstanceMethods
# Whether this page is a proxy # Whether this page is a proxy
# rubocop:disable TrivialAccessors
# @return [Boolean] # @return [Boolean]
def proxy? def proxy?
!!@proxied_to @proxied_to
end end
# Set this page to proxy to a target path # Set this page to proxy to a target path
@ -52,6 +53,7 @@ module Middleman
proxy_resource proxy_resource
end end
# rubocop:disable AccessorMethodName
def get_source_file def get_source_file
if proxy? if proxy?
proxied_to_resource.source_file proxied_to_resource.source_file
@ -97,14 +99,14 @@ module Middleman
# :locals, :ignore to hide the proxy target, :layout, and :directory_indexes. # :locals, :ignore to hide the proxy target, :layout, and :directory_indexes.
# @return [void] # @return [void]
def proxy(path, target, opts={}, &block) def proxy(path, target, opts={}, &block)
metadata = { :options => {}, :locals => {}, :blocks => [] } metadata = { options: {}, locals: {}, blocks: [] }
metadata[:blocks] << block if block_given? metadata[:blocks] << block if block_given?
metadata[:locals] = opts.delete(:locals) || {} metadata[:locals] = opts.delete(:locals) || {}
@app.ignore(target) if opts.delete(:ignore) @app.ignore(target) if opts.delete(:ignore)
metadata[:options] = opts metadata[:options] = opts
@proxy_configs << ProxyConfiguration.new(:path => path, :target => target, :metadata => metadata) @proxy_configs << ProxyConfiguration.new(path: path, target: target, metadata: metadata)
@app.sitemap.rebuild_resource_list!(:added_proxy) @app.sitemap.rebuild_resource_list!(:added_proxy)
end end

View file

@ -35,9 +35,7 @@ module Middleman
# @param [String] path # @param [String] path
# @param [Hash] opts The :to value gives a target path # @param [Hash] opts The :to value gives a target path
def create_redirect(path, opts={}, &block) def create_redirect(path, opts={}, &block)
if block_given? opts[:template] = block if block_given?
opts[:template] = block
end
@redirects[path] = opts @redirects[path] = opts
@ -72,10 +70,10 @@ module Middleman
true true
end end
def render(*args, &block) def render(*)
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

View file

@ -37,7 +37,7 @@ module Middleman
# differs from the output path # differs from the output path
def create_endpoint(path, opts={}, &block) def create_endpoint(path, opts={}, &block)
endpoint = { endpoint = {
:request_path => path request_path: path
} }
if block_given? if block_given?
@ -79,7 +79,7 @@ module Middleman
true true
end end
def render(*args, &block) def render(*)
return output.call if output return output.call if output
end end

View file

@ -69,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.exist?(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

@ -73,33 +73,33 @@ module Middleman
end end
def where(constraints_hash) def where(constraints_hash)
selector_hash = constraints_hash.reject { |key, value| !key.is_a? Selector } selector_hash = constraints_hash.reject { |key, _| !key.is_a? Selector }
symbol_hash = constraints_hash.reject { |key, value| key.is_a? Selector } symbol_hash = constraints_hash.reject { |key, _| 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,
:limit => @limit limit: @limit
}.merge(new_opts) }.merge(new_opts)
end end
def order_by(field) def order_by(field)
Query.new @model, opts(:order_by => field.is_a?(Symbol) ? { field => :asc } : field) Query.new @model, opts(order_by: field.is_a?(Symbol) ? { field => :asc } : field)
end end
def offset(number) def offset(number)
Query.new @model, opts(:offset => number) Query.new @model, opts(offset: number)
end end
def limit(number) def limit(number)
Query.new @model, opts(:limit => number) Query.new @model, opts(limit: number)
end end
def first def first
@ -111,13 +111,9 @@ module Middleman
end end
def all def all
result = @model.select(:where => @where, :order_by => @order_by) result = @model.select(where: @where, order_by: @order_by)
if @offset.present? result = result.last([result.size - @offset, 0].max) if @offset.present?
result = result.last([result.size - @offset, 0].max) result = result.first(@limit) if @limit.present?
end
if @limit.present?
result = result.first(@limit)
end
result result
end end
end end

View file

@ -11,7 +11,7 @@ module Middleman
# @return [Middleman::Application] # @return [Middleman::Application]
attr_reader :app attr_reader :app
delegate :logger, :instrument, :to => :app delegate :logger, :instrument, to: :app
# @return [Middleman::Sitemap::Store] # @return [Middleman::Sitemap::Store]
attr_reader :store attr_reader :store
@ -44,7 +44,7 @@ module Middleman
@source_file = source_file @source_file = source_file
@destination_path = @path @destination_path = @path
@local_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] } @local_metadata = { options: {}, locals: {}, page: {}, blocks: [] }
end end
# Whether this resource has a template file # Whether this resource has a template file
@ -60,15 +60,11 @@ 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.key?(:blocks) result[:blocks] += file_meta.delete(:blocks) if file_meta.key?(:blocks)
result[:blocks] += file_meta.delete(:blocks)
end
result.deep_merge!(file_meta) result.deep_merge!(file_meta)
local_meta = @local_metadata.dup local_meta = @local_metadata.dup
if local_meta.key?(:blocks) result[:blocks] += local_meta.delete(:blocks) if local_meta.key?(:blocks)
result[:blocks] += local_meta.delete(:blocks)
end
result.deep_merge!(local_meta) result.deep_merge!(local_meta)
result[:blocks] = result[:blocks].flatten.compact result[:blocks] = result[:blocks].flatten.compact
@ -79,9 +75,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.key?(:blocks) @local_metadata[:blocks] += metadata.delete(:blocks) if metadata.key?(:blocks)
@local_metadata[:blocks] += metadata.delete(:blocks)
end
@local_metadata.deep_merge!(metadata) @local_metadata.deep_merge!(metadata)
@local_metadata[:blocks] += [block] if block_given? @local_metadata[:blocks] += [block] if block_given?
end end
@ -103,13 +97,11 @@ module Middleman
# Render this resource # Render this resource
# @return [String] # @return [String]
def render(opts={}, locs={}, &block) def render(opts={}, locs={}, &block)
unless template? return app.template_data_for_file(source_file) unless template?
return app.template_data_for_file(source_file)
end
relative_source = Pathname(source_file).relative_path_from(Pathname(app.root)) relative_source = Pathname(source_file).relative_path_from(Pathname(app.root))
instrument 'render.resource', :path => relative_source, :destination_path => destination_path do instrument 'render.resource', path: relative_source, destination_path: destination_path do
md = metadata.dup md = metadata.dup
opts = md[:options].deep_merge(opts) opts = md[:options].deep_merge(opts)
@ -124,9 +116,7 @@ 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.key?(:page) app.data.store('page', md[:page]) if md.key?(:page)
app.data.store('page', md[:page])
end
blocks = Array(md[:blocks]).dup blocks = Array(md[:blocks]).dup
blocks << block if block_given? blocks << block if block_given?

View file

@ -49,12 +49,13 @@ module Middleman
# @param [Symbol] name Name of the manipulator for debugging # @param [Symbol] name Name of the manipulator for debugging
# @param [Class, Module] inst Abstract namespace which can update the resource list # @param [Class, Module] inst Abstract namespace which can update the resource list
# @return [void] # @return [void]
def register_resource_list_manipulator(name, inst, unused=true) def register_resource_list_manipulator(name, inst, *)
@resource_list_manipulators << [name, inst] @resource_list_manipulators << [name, inst]
rebuild_resource_list!(:registered_new) rebuild_resource_list!(:registered_new)
end end
# Rebuild the list of resources from scratch, using registed manipulators # Rebuild the list of resources from scratch, using registed manipulators
# rubocop:disable UnusedMethodArgument
# @return [void] # @return [void]
def rebuild_resource_list!(reason=nil) def rebuild_resource_list!(reason=nil)
@lock.synchronize do @lock.synchronize do
@ -117,7 +118,7 @@ module Middleman
# @param [String] source_file # @param [String] source_file
# @return [Hash] # @return [Hash]
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.reduce(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)
@ -151,7 +152,7 @@ module Middleman
def metadata_for_path(request_path) def metadata_for_path(request_path)
return @_cached_metadata[request_path] if @_cached_metadata[request_path] return @_cached_metadata[request_path] if @_cached_metadata[request_path]
blank_metadata = { :options => {}, :locals => {}, :page => {}, :blocks => [] } blank_metadata = { options: {}, locals: {}, page: {}, blocks: [] }
@_cached_metadata[request_path] = provides_metadata_for_path.reduce(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
@ -252,9 +253,7 @@ module Middleman
if @app.respond_to? :langs if @app.respond_to? :langs
path_bits = path.split('.') path_bits = path.split('.')
lang = path_bits.last lang = path_bits.last
if @app.langs.include?(lang.to_sym) return path_bits[0..-2].join('.') if @app.langs.include?(lang.to_sym)
return path_bits[0..-2].join('.')
end
end end
path path

View file

@ -39,13 +39,13 @@ module Middleman::Templates
end end
# Required path for the new project to be generated # Required path for the new project to be generated
argument :location, :type => :string argument :location, type: :string
# Name of the template being used to generate the project. # Name of the template being used to generate the project.
class_option :template, :default => 'default' class_option :template, default: 'default'
# Output a config.ru file for Rack if --rack is passed # Output a config.ru file for Rack if --rack is passed
class_option :rack, :type => :boolean, :default => false class_option :rack, type: :boolean, default: false
# Write a Rack config.ru file for project # Write a Rack config.ru file for project
# @return [void] # @return [void]
@ -54,8 +54,8 @@ module Middleman::Templates
template 'shared/config.ru', File.join(location, 'config.ru') template 'shared/config.ru', File.join(location, 'config.ru')
end end
class_option :'skip-bundle', :type => :boolean, :default => false class_option :'skip-bundle', type: :boolean, default: false
class_option :'skip-gemfile', :type => :boolean, :default => false class_option :'skip-gemfile', type: :boolean, default: false
# Write a Bundler Gemfile file for project # Write a Bundler Gemfile file for project
# @return [void] # @return [void]
@ -70,7 +70,7 @@ module Middleman::Templates
end end
# Output a .gitignore file # Output a .gitignore file
class_option :'skip-git', :type => :boolean, :default => false class_option :'skip-git', type: :boolean, default: false
# Write a .gitignore file for project # Write a .gitignore file for project
# @return [void] # @return [void]
@ -94,9 +94,8 @@ require 'middleman-core/templates/mobile'
require 'middleman-more/templates/smacss' require 'middleman-more/templates/smacss'
# Local templates # Local templates
if ENV['HOME'] # Sometimes HOME doesn't exist, in which case there's no point to local templates # Sometimes HOME doesn't exist, in which case there's no point to local templates
require 'middleman-core/templates/local' require 'middleman-core/templates/local' if ENV['HOME']
end
# Barebones template # Barebones template
require 'middleman-core/templates/empty' require 'middleman-core/templates/empty'

View file

@ -1,14 +1,14 @@
# Default Middleman template # Default Middleman template
class Middleman::Templates::Default < Middleman::Templates::Base class Middleman::Templates::Default < Middleman::Templates::Base
class_option 'css_dir', class_option 'css_dir',
:default => 'stylesheets', default: 'stylesheets',
:desc => 'The path to the css files' desc: 'The path to the css files'
class_option 'js_dir', class_option 'js_dir',
:default => 'javascripts', default: 'javascripts',
:desc => 'The path to the javascript files' desc: 'The path to the javascript files'
class_option 'images_dir', class_option 'images_dir',
:default => 'images', default: 'images',
:desc => 'The path to the image files' desc: 'The path to the image files'
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]

View file

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

View file

@ -1,14 +1,14 @@
# HTML5 Boilerplate template # HTML5 Boilerplate template
class Middleman::Templates::Html5 < Middleman::Templates::Base class Middleman::Templates::Html5 < Middleman::Templates::Base
class_option 'css_dir', class_option 'css_dir',
:default => 'css', default: 'css',
:desc => 'The path to the css files' desc: 'The path to the css files'
class_option 'js_dir', class_option 'js_dir',
:default => 'js', default: 'js',
:desc => 'The path to the javascript files' desc: 'The path to the javascript files'
class_option 'images_dir', class_option 'images_dir',
:default => 'img', default: 'img',
:desc => 'The path to the image files' desc: 'The path to the image files'
# Templates are relative to this file # Templates are relative to this file
# @return [String] # @return [String]

View file

@ -1,9 +1,9 @@
# 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'
class_option :images_dir, :default => 'img' class_option :images_dir, default: 'img'
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]

View file

@ -6,6 +6,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
# rubocop:disable UnderscorePrefixedVariableName
def capture_from_template(*args, &block) def capture_from_template(*args, &block)
self.output_buffer, _buf_was = '', output_buffer self.output_buffer, _buf_was = '', output_buffer
raw = block.call(*args) raw = block.call(*args)
@ -38,6 +39,7 @@ class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
helpers do helpers do
# Make all block content html_safe # Make all block content html_safe
# rubocop:disable Semicolon
def content_tag(name, content=nil, options=nil, &block) def content_tag(name, content=nil, options=nil, &block)
if block_given? if block_given?
options = content if content.is_a?(Hash) options = content if content.is_a?(Hash)

View file

@ -55,10 +55,10 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
end end
delegate :logger, :to => :app delegate :logger, to: :app
def langs def langs
@_langs ||= get_known_languages @_langs ||= known_languages
end end
# Update the main sitemap resource list # Update the main sitemap resource list
@ -115,7 +115,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
def metadata_for_path(url) def metadata_for_path(url)
if d = get_localization_data(url) if d = localization_data(url)
lang, page_id = d lang, page_id = d
else else
# Default to the @mount_at_root lang # Default to the @mount_at_root lang
@ -129,18 +129,18 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
locals = { locals = {
:lang => lang, lang: lang,
:page_id => page_id page_id: page_id
} }
{ {
:blocks => [instance_vars], blocks: [instance_vars],
:locals => locals, locals: locals,
:options => { :lang => lang } options: { lang: lang }
} }
end end
def get_known_languages def known_languages
if options[:langs] if options[:langs]
Array(options[:langs]).map(&:to_sym) Array(options[:langs]).map(&:to_sym)
else else
@ -154,7 +154,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
end end
end end
def get_localization_data(path) def localization_data(path)
@_localization_data ||= {} @_localization_data ||= {}
@_localization_data[path] @_localization_data[path]
end end
@ -177,7 +177,7 @@ class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
def build_resource(path, source_path, page_id, lang) def build_resource(path, source_path, page_id, lang)
old_locale = ::I18n.locale old_locale = ::I18n.locale
::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)
'/' '/'

View file

@ -16,7 +16,7 @@ class Middleman::Extensions::AssetHash < ::Middleman::Extension
# Allow specifying regexes to ignore, plus always ignore apple touch icons # Allow specifying regexes to ignore, plus always ignore apple touch icons
@ignore = Array(options.ignore) + [/^apple-touch-icon/] @ignore = Array(options.ignore) + [/^apple-touch-icon/]
app.use Middleware, :exts => options.exts, :middleman_app => app, :ignore => @ignore app.use Middleware, exts: options.exts, middleman_app: app, ignore: @ignore
end end
# Update the main sitemap resource list # Update the main sitemap resource list

View file

@ -24,7 +24,7 @@ class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
if File.exist?(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
params[:height] = height params[:height] = height
rescue FastImage::UnknownImageType rescue FastImage::UnknownImageType

View file

@ -14,15 +14,15 @@ class Middleman::Extensions::MinifyCss < ::Middleman::Extension
chosen_compressor = app.config[:css_compressor] || options[:compressor] || SassCompressor chosen_compressor = app.config[:css_compressor] || options[:compressor] || SassCompressor
# Setup Rack middleware to minify CSS # Setup Rack middleware to minify CSS
app.use Rack, :compressor => chosen_compressor, app.use Rack, compressor: chosen_compressor,
:ignore => Array(options[:ignore]) + [/\.min\./], ignore: Array(options[:ignore]) + [/\.min\./],
:inline => options[:inline] inline: options[:inline]
end end
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 = options.merge(:style => :compressed) root_node.options = options.merge(style: :compressed)
root_node.render.strip root_node.render.strip
end end
end end

View file

@ -17,9 +17,9 @@ class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
end end
# Setup Rack middleware to minify CSS # Setup Rack middleware to minify CSS
app.use Rack, :compressor => chosen_compressor, app.use Rack, compressor: chosen_compressor,
:ignore => Array(options[:ignore]) + [/\.min\./], ignore: Array(options[:ignore]) + [/\.min\./],
:inline => options[:inline] inline: options[:inline]
end end
# Rack middleware to look for JS and compress it # Rack middleware to look for JS and compress it

View file

@ -1,14 +1,14 @@
# SMACSS # SMACSS
class Middleman::Templates::Smacss < Middleman::Templates::Base class Middleman::Templates::Smacss < Middleman::Templates::Base
class_option 'css_dir', class_option 'css_dir',
:default => 'stylesheets', default: 'stylesheets',
:desc => 'The path to the css files' desc: 'The path to the css files'
class_option 'js_dir', class_option 'js_dir',
:default => 'javascripts', default: 'javascripts',
:desc => 'The path to the javascript files' desc: 'The path to the javascript files'
class_option 'images_dir', class_option 'images_dir',
:default => 'images', default: 'images',
:desc => 'The path to the image files' desc: 'The path to the image files'
# Template files are relative to this file # Template files are relative to this file
# @return [String] # @return [String]