repo stringlengths 5 92 | file_url stringlengths 80 287 | file_path stringlengths 5 197 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 15:37:27 2026-01-04 17:58:21 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/stylus-preview-app/config.rb | middleman-core/fixtures/stylus-preview-app/config.rb | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false | |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/cache-buster-app/config.rb | middleman-core/fixtures/cache-buster-app/config.rb | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false | |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/frontmatter-neighbor-app/config.rb | middleman-core/fixtures/frontmatter-neighbor-app/config.rb | ignore '*.frontmatter'
# Reads neighbor for every file on every refresh.
# TODO: Optimize
class NeighborFrontmatter < ::Middleman::Extension
self.resource_list_manipulator_priority = 81
def manipulate_resource_list(resources)
resources.each do |resource|
next unless resource.file_descriptor
neighbor = "#{resource.file_descriptor[:relative_path]}.frontmatter"
file = app.files.find(:source, neighbor)
next unless file
fmdata = ::Middleman::Util::Data.parse(file, app.config[:frontmatter_delims], :yaml).first
opts = fmdata.extract!(:layout, :layout_engine, :renderer_options, :directory_index, :content_type)
opts[:renderer_options].symbolize_keys! if opts.key?(:renderer_options)
ignored = fmdata.delete(:ignored)
resource.add_metadata options: opts, page: fmdata
resource.ignore! if ignored == true && !resource.is_a?(::Middleman::Sitemap::ProxyResource)
end
end
end
Middleman::Extensions.register :neighbor_frontmatter, NeighborFrontmatter unless Middleman::Extensions.registered.include? :neighbor_frontmatter
activate :neighbor_frontmatter
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/multiple-sources-app/config.rb | middleman-core/fixtures/multiple-sources-app/config.rb | files.watch :source, path: File.join(root, 'source0'), priority: 100
files.watch :source, path: File.join(root, 'source1')
files.watch :source, path: File.join(root, 'source2') | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/chained-app/config.rb | middleman-core/fixtures/chained-app/config.rb | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false | |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/proxy-pages-app/config.rb | middleman-core/fixtures/proxy-pages-app/config.rb | # -*- coding: utf-8 -*-
proxy "/fake.html", "/real.html", layout: false
proxy "fake2.html", "/real.html", layout: false
proxy "fake3.html", "real.html", layout: false
proxy "/fake4.html", "real.html", layout: false
proxy "/target_ignore.html", "/should_be_ignored3.html", ignore: true
proxy "target_ignore2.html", "/should_be_ignored6.html", ignore: true
proxy "target_ignore3.html", "should_be_ignored7.html", ignore: true
proxy "/target_ignore4.html", "should_be_ignored8.html", ignore: true
%w(one two).each do |num|
proxy "/fake/#{num}.html", "/real/index.html", ignore: true, locals: { num: num }
proxy "fake2/#{num}.html", "/real/index.html", ignore: true, locals: { num: num }
proxy "fake3/#{num}.html", "real/index.html", ignore: true, locals: { num: num }
end
proxy "明日がある.html", "/real.html", layout: false
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/i18n-mixed-sources/config.rb | middleman-core/fixtures/i18n-mixed-sources/config.rb | activate :i18n, mount_at_root: :en, langs: [:en, :es]
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/wildcard-app/config.rb | middleman-core/fixtures/wildcard-app/config.rb | page "/admin/*", layout: :admin
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/markdown-app/config.rb | middleman-core/fixtures/markdown-app/config.rb | set :markdown, smartypants: true
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/page-helper-layout-block-app/config.rb | middleman-core/fixtures/page-helper-layout-block-app/config.rb | page "/path/*", layout: "alt"
# Doesn't work, and shouldn't
# page "/path/*" do
# set :layout, "alt"
# end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/frontmatter-settings-neighbor-app/config.rb | middleman-core/fixtures/frontmatter-settings-neighbor-app/config.rb | # Proxy ignored.html, which should ignore itself through a frontmatter
proxy 'proxied.html', 'ignored.html'
proxy 'proxied_with_frontmatter.html', 'ignored.html'
page 'override_layout.html', layout: :alternate
page 'page_mentioned.html'
ignore '*.frontmatter'
# Reads neighbor for every file on every refresh.
class NeighborFrontmatter < ::Middleman::Extension
self.resource_list_manipulator_priority = 81
def manipulate_resource_list(resources)
resources.each do |resource|
next unless resource.file_descriptor
next if resource.file_descriptor[:relative_path].extname == '.frontmatter'
[
"#{resource.url.sub(/^\//, '')}.frontmatter",
"#{resource.file_descriptor[:relative_path]}.frontmatter"
].each do |n|
file = app.files.find(:source, n)
apply_neighbor_data(resource, file) if file
end
end
end
def apply_neighbor_data(resource, file)
fmdata = ::Middleman::Util::Data.parse(file, app.config[:frontmatter_delims], :yaml).first
opts = fmdata.extract!(:layout, :layout_engine, :renderer_options, :directory_index, :content_type)
opts[:renderer_options].symbolize_keys! if opts.key?(:renderer_options)
ignored = fmdata.delete(:ignored)
resource.add_metadata options: opts, page: fmdata
resource.ignore! if ignored == true && !resource.is_a?(::Middleman::Sitemap::ProxyResource)
end
end
Middleman::Extensions.register :neighbor_frontmatter, NeighborFrontmatter unless Middleman::Extensions.registered.include? :neighbor_frontmatter
activate :neighbor_frontmatter
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/more-traversal-app/config.rb | middleman-core/fixtures/more-traversal-app/config.rb | activate :directory_indexes
proxy "/sub/fake.html", "/proxied.html", ignore: true
proxy "/sub/fake2.html", "/proxied.html", ignore: true
proxy "/directory-indexed/fake.html", "/proxied.html", ignore: true
proxy "/directory-indexed/fake2.html", "/proxied.html", ignore: true
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/automatic-alt-tags-app/config.rb | middleman-core/fixtures/automatic-alt-tags-app/config.rb | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false | |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/i-8859-1-app/config.rb | middleman-core/fixtures/i-8859-1-app/config.rb | set :encoding, "ISO-8859-1"
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/data-with-aliases-app/config.rb | middleman-core/fixtures/data-with-aliases-app/config.rb | data.pages.each do |p|
proxy p.from, p.to, locals: { content: p.content }
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/empty-app/not-config.rb | middleman-core/fixtures/empty-app/not-config.rb | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false | |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/sinatra-app/config.rb | middleman-core/fixtures/sinatra-app/config.rb | require "sinatra"
class MySinatra < Sinatra::Base
set :host_authorization, { permitted_hosts: "www.example.com" }
get "/" do
"Hello World (Sinatra)"
end
get "/derp.html" do
"De doo"
end
end
map "/sinatra" do
run MySinatra
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/asset-host-app/config.rb | middleman-core/fixtures/asset-host-app/config.rb | activate :asset_host, host: "http://assets1.example.com"
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/build-with-errors-app/config.rb | middleman-core/fixtures/build-with-errors-app/config.rb | set :layout, false
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/fixtures/extension-hooks-app/config.rb | middleman-core/fixtures/extension-hooks-app/config.rb | set :layout, false
class MyFeature < Middleman::Extension
def initialize(app, options_hash = {}, &block)
super
app.before do
puts '/// before ///'
end
app.ready do
puts '/// ready ///'
end
app.before_render do |body, path, locs, template_class|
puts "/// before_render ///"
end
app.after_render do |content, path, locs, template_class|
puts "/// after_render ///"
end
app.before_build do |builder|
puts "/// before_build ///"
end
app.after_build do |builder|
puts "/// after_build ///"
end
end
def after_configuration
puts '/// after_configuration ///'
end
end
::Middleman::Extensions.register(:my_feature, MyFeature)
activate :my_feature
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/features/support/env.rb | middleman-core/features/support/env.rb | ENV["TEST"] = "true"
require 'sassc'
require 'simplecov'
SimpleCov.root(File.expand_path(File.dirname(__FILE__) + '/../..'))
SimpleCov.start
require "rspec"
RSpec.configure do |config|
config.expect_with :rspec do |expectations|
expectations.max_formatted_output_length = nil
end
end
PROJECT_ROOT_PATH = File.dirname(File.dirname(File.dirname(__FILE__)))
require File.join(PROJECT_ROOT_PATH, 'lib', 'middleman-core')
require File.join(PROJECT_ROOT_PATH, 'lib', 'middleman-core', 'step_definitions')
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/features/support/preserve_mime_types.rb | middleman-core/features/support/preserve_mime_types.rb | Around('@preserve_mime_types') do |_scenario, block|
mime_types = ::Rack::Mime::MIME_TYPES.clone
block.call
::Rack::Mime::MIME_TYPES.replace mime_types
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/spec_helper.rb | middleman-core/spec/spec_helper.rb | require 'simplecov'
SimpleCov.root(File.expand_path(File.dirname(__FILE__) + '/..'))
SimpleCov.start
require 'aruba/api'
RSpec.configure do |config|
config.include Aruba::Api
end
require_relative 'support/given'
RSpec.configure do |config|
config.filter_run :focus
config.run_all_when_everything_filtered = true
config.default_formatter = 'doc' if config.files_to_run.one?
config.order = :random
Kernel.srand config.seed
config.color = true
config.expect_with :rspec do |expectations|
expectations.syntax = :expect
end
config.mock_with :rspec do |mocks|
mocks.syntax = :expect
mocks.verify_partial_doubles = true
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/support/given.rb | middleman-core/spec/support/given.rb | module Given
ROOT = File.expand_path( '../..', File.dirname( File.realpath(__FILE__) ) )
TMP = File.join( ROOT, 'tmp' )
class << self
def fixture name
cleanup!
`rsync -av #{File.join( ROOT, 'fixtures', name )}/ #{TMP}/`
Dir.chdir TMP
ENV['MM_ROOT'] = TMP
end
def no_file name
FileUtils.rm name, force: true
end
def symlink source, destination
no_file destination
FileUtils.symlink File.expand_path(source),
File.expand_path(destination),
force: true
end
def file name, content
file_path = File.join( TMP, name )
FileUtils.mkdir_p( File.dirname(file_path) )
File.open( file_path, 'w' ) do |file|
file.write content
end
end
def cleanup!
Dir.chdir ROOT
if File.exist? TMP
`rm -rf #{TMP}`
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/dns_resolver_spec.rb | middleman-core/spec/middleman-core/dns_resolver_spec.rb | require 'spec_helper'
require 'middleman-core/dns_resolver'
RSpec.describe Middleman::DnsResolver do
subject(:resolver) do
described_class.new(
hosts_resolver: hosts_resolver,
local_link_resolver: local_link_resolver,
network_resolver: network_resolver
)
end
let(:hosts_resolver) { instance_double('Middleman::DnsResolver::HostsResolver') }
let(:local_link_resolver) { instance_double('Middleman::DnsResolver::LocalLinkResolver') }
let(:network_resolver) { instance_double('Middleman::DnsResolver::NetworkResolver') }
before :each do
allow(network_resolver).to receive(:timeouts=)
end
describe '#names_for' do
context 'when hosts resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getnames).with(unresolved_ip).and_return(resolved_names)
expect(local_link_resolver).not_to receive(:getnames)
expect(network_resolver).not_to receive(:getnames)
end
let(:unresolved_ip) { '127.0.0.1' }
let(:resolved_names) { %w(localhost) }
it { expect(resolver.names_for(unresolved_ip)).to eq resolved_names }
end
context 'when local link resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getnames).with(unresolved_ip).and_return([])
expect(local_link_resolver).to receive(:getnames).with(unresolved_ip).and_return(resolved_names)
expect(network_resolver).not_to receive(:getnames)
end
let(:unresolved_ip) { '127.0.0.1' }
let(:resolved_names) { %w(localhost) }
it { expect(resolver.names_for(unresolved_ip)).to eq resolved_names }
end
context 'when network resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getnames).with(unresolved_ip).and_return([])
expect(local_link_resolver).to receive(:getnames).with(unresolved_ip).and_return([])
expect(network_resolver).to receive(:getnames).with(unresolved_ip).and_return(resolved_names)
end
let(:unresolved_ip) { '127.0.0.1' }
let(:resolved_names) { %w(localhost) }
it { expect(resolver.names_for(unresolved_ip)).to eq resolved_names }
end
end
describe '#ips_for' do
context 'when hosts resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getaddresses).with(unresolved_ips).and_return(resolved_name)
expect(local_link_resolver).not_to receive(:getaddresses)
expect(network_resolver).not_to receive(:getaddresses)
end
let(:unresolved_ips) { '127.0.0.1' }
let(:resolved_name) { %w(localhost) }
it { expect(resolver.ips_for(unresolved_ips)).to eq resolved_name }
end
context 'when local link resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getaddresses).with(unresolved_ips).and_return([])
expect(local_link_resolver).to receive(:getaddresses).with(unresolved_ips).and_return(resolved_name)
expect(network_resolver).not_to receive(:getaddresses)
end
let(:unresolved_ips) { '127.0.0.1' }
let(:resolved_name) { %w(localhost) }
it { expect(resolver.ips_for(unresolved_ips)).to eq resolved_name }
end
context 'when network resolver can resolve name' do
before :each do
expect(hosts_resolver).to receive(:getaddresses).with(unresolved_ips).and_return([])
expect(local_link_resolver).to receive(:getaddresses).with(unresolved_ips).and_return([])
expect(network_resolver).to receive(:getaddresses).with(unresolved_ips).and_return(resolved_name)
end
let(:unresolved_ips) { '127.0.0.1' }
let(:resolved_name) { %w(localhost) }
it { expect(resolver.ips_for(unresolved_ips)).to eq resolved_name }
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/callbacks_spec.rb | middleman-core/spec/middleman-core/callbacks_spec.rb | # require 'spec_helper'
require 'middleman-core/callback_manager'
describe ::Middleman::CallbackManager do
it "adds a simple key" do
counters = {
test1: 0,
test2: 0,
test3: 0
}
m = ::Middleman::CallbackManager.new
m.add(:test3) { counters[:test3] += 1 }
m.add(:test1) { counters[:test1] += 1 }
m.add(:test2) { counters[:test2] += 1 }
m.add(:test1) { counters[:test1] += 1 }
m.add(:test2) { counters[:test2] += 1 }
m.add(:test1) { counters[:test1] += 1 }
m.add(:test3) { counters[:test3] += 1 }
m.execute(:test1)
m.execute(:test2)
expect(counters[:test1]).to eq 3
expect(counters[:test2]).to eq 2
expect(counters[:test3]).to eq 0
end
it "callbacks run in order" do
result = []
m = ::Middleman::CallbackManager.new
m.add(:test) { result.push(1) }
m.add(:test) { result.push(2) }
m.add(:test) { result.push(3) }
m.execute(:test)
expect(result.join('')).to eq '123'
end
it "adds a nested key" do
counters = {
test1: 0,
test1a: 0
}
m = ::Middleman::CallbackManager.new
m.add([:test1, :a]) { |n| counters[:test1a] += n }
m.add(:test1) { counters[:test1] += 1 }
m.execute([:test1, :a], [2])
m.execute([:test1, :b], [5])
expect(counters[:test1]).to eq 0
expect(counters[:test1a]).to eq 2
end
it "works in isolation" do
m1 = ::Middleman::CallbackManager.new
m2 = ::Middleman::CallbackManager.new
counters = {
test1: 0,
test2: 0
}
m1.add(:test1) { |n| counters[:test1] += n }
m2.add(:test1) { |n| counters[:test2] += n }
m1.execute(:test1, [2])
m2.execute(:test1, [5])
m1.execute(:test2, [20])
m2.execute(:test2, [50])
expect(counters[:test1]).to eq 2
expect(counters[:test2]).to eq 5
end
it "installs to arbitrary instances" do
instance = Class.new(Object).new
m = ::Middleman::CallbackManager.new
m.install_methods!(instance, [:ready])
counter = 0
instance.ready { |n| counter += n }
instance.execute_callbacks(:ready, [2])
instance.execute_callbacks(:ready2, [10])
instance.execute_callbacks([:ready], [20])
instance.execute_callbacks([:ready, :two], [20])
expect(counter).to eq 2
end
it "executes in default scope" do
instance = Class.new(Object).new
m = ::Middleman::CallbackManager.new
m.install_methods!(instance, [:ready])
internal_self = nil
instance.ready do
internal_self = self
end
instance.execute_callbacks(:ready)
expect(internal_self) === instance
end
it "executes in custom scope" do
instance = Class.new(Object).new
m = ::Middleman::CallbackManager.new
m.install_methods!(instance, [:ready])
external_class = Struct.new(:counter, :scope) do
def when_ready(n)
self[:scope] = self
self[:counter] += n
end
end
external_instance = external_class.new(0, nil)
instance.ready(&external_instance.method(:when_ready))
instance.execute_callbacks(:ready, [5])
expect(external_instance[:scope]).to eq external_instance
expect(external_instance[:counter]).to eq 5
end
end | ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/util_spec.rb | middleman-core/spec/middleman-core/util_spec.rb | require 'spec_helper'
require 'middleman-core'
describe Middleman::Util do
describe "::path_match" do
it "matches a literal string" do
expect(Middleman::Util.path_match '/index.html', '/index.html').to be true
end
it "won't match a wrong string" do
expect(Middleman::Util.path_match '/foo.html', '/index.html').to be false
end
it "won't match a partial string" do
expect(Middleman::Util.path_match 'ind', '/index.html').to be false
end
it "works with a regex" do
expect(Middleman::Util.path_match /\.html$/, '/index.html').to be true
expect(Middleman::Util.path_match /\.js$/, '/index.html').to be false
end
it "works with a proc" do
matcher = lambda {|p| p.length > 5 }
expect(Middleman::Util.path_match matcher, '/index.html').to be true
expect(Middleman::Util.path_match matcher, '/i').to be false
end
it "works with globs" do
expect(Middleman::Util.path_match '/foo/*.html', '/foo/index.html').to be true
expect(Middleman::Util.path_match '/foo/*.html', '/foo/index.js').to be false
expect(Middleman::Util.path_match '/bar/*.html', '/foo/index.js').to be false
expect(Middleman::Util.path_match '/foo/*', '/foo/bar/index.html').to be true
expect(Middleman::Util.path_match '/foo/**/*', '/foo/bar/index.html').to be true
expect(Middleman::Util.path_match '/foo/**', '/foo/bar/index.html').to be true
end
end
describe "::binary?" do
%w(plain.txt unicode.txt unicode).each do |file|
it "recognizes #{file} as not binary" do
expect(Middleman::Util.binary?(File.join(File.dirname(__FILE__), "binary_spec/#{file}"))).to be false
end
end
%w(middleman.png middleman stars.svgz).each do |file|
it "recognizes #{file} as binary" do
expect(Middleman::Util.binary?(File.join(File.dirname(__FILE__), "binary_spec/#{file}"))).to be true
end
end
end
describe "::recursively_enhance" do
it "returns Hashie extended Hash if given a hash" do
input = {test: "subject"}
subject = Middleman::Util.recursively_enhance input
expect( subject.test ).to eq "subject"
end
it "returns Array with strings, or IndifferentHash, true, false" do
indifferent_hash = {test: "subject"}
regular_hash = {regular: "hash"}
input = [ indifferent_hash, regular_hash, true, false ]
subject = Middleman::Util.recursively_enhance input
expect( subject[1].regular ).to eq "hash"
expect( subject[2] ).to eq true
expect( subject[3] ).to eq false
end
end
describe "::asset_url" do
after(:each) do
Given.cleanup!
end
context "when http_prefix is activated" do
before(:each) do
Given.fixture 'clean-dir-app'
Given.file 'source/images/blank.gif', ''
@mm = Middleman::Application.new do
config[:http_prefix] = 'http_prefix'
end
end
it "returns path with http_prefix pre-pended if resource is found" do
expect( Middleman::Util.asset_url( @mm, 'blank.gif', 'images', http_prefix: 'http_prefix' ) ).to eq 'http_prefix/images/blank.gif'
end
it "returns path with http_prefix pre-pended if resource is not found" do
expect( Middleman::Util.asset_url( @mm, 'missing.gif', 'images', http_prefix: 'http_prefix' ) ).to eq 'http_prefix/images/missing.gif'
end
end
it "returns path relative to the provided current_resource" do
Given.fixture 'clean-dir-app'
Given.file 'source/a-path/index.html', ''
Given.file 'source/a-path/images/blank.gif', ''
@mm = Middleman::Application.new
current_resource = @mm.sitemap.find_resource_by_path('a-path/index.html')
expect( Middleman::Util.asset_url( @mm, 'images/blank.gif', 'images', current_resource: current_resource ) ).to eq '/a-path/images/blank.gif'
end
context "when relative is true" do
before(:each) do
Given.fixture 'relative-assets-app'
@mm = Middleman::Application.new
end
it "returns path relative to the provided current_resource" do
current_resource = instance_double("Middleman::Sitemap::Resource", destination_path: 'a-path/index.html', path: 'a-path/index.html')
expect( Middleman::Util.asset_url( @mm, 'blank.gif', 'images', current_resource: current_resource,
relative: true ) ).to eq '../images/blank.gif'
end
context "when the asset is stored in the same directory as current_resource" do
before do
Given.file 'source/a-path/index.html', ''
Given.file 'source/a-path/blank.gif', ''
@mm = Middleman::Application.new
end
it "returns path relative to the provided current_resource" do
current_resource = @mm.sitemap.find_resource_by_path('a-path/index.html')
expect( Middleman::Util.asset_url( @mm, 'blank.gif', 'images', current_resource: current_resource,
relative: true) ).to eq 'blank.gif'
end
end
it "raises error if not given a current_resource" do
expect{
Middleman::Util.asset_url( @mm, 'blank.gif', 'images', relative: true )
}.to raise_error ArgumentError
end
end
it "returns path if it is already a full path" do
expect( Middleman::Util.asset_url( @mm, 'http://example.com' ) ).to eq 'http://example.com'
expect( Middleman::Util.asset_url( @mm, 'data:example' ) ).to eq 'data:example'
end
it "returns a resource url if given a resource's destination path" do
Given.fixture 'clean-dir-app' # includes directory indexes extension
Given.file 'source/how/about/that.html', ''
@mm = Middleman::Application.new
expect( Middleman::Util.asset_url( @mm, '/how/about/that/index.html' ) ).to eq '/how/about/that/'
end
it "returns a resource url if given a resources path" do
Given.fixture 'clean-dir-app' # includes directory indexes extension
Given.file 'source/how/about/that.html', ''
@mm = Middleman::Application.new
expect( Middleman::Util.asset_url( @mm, '/how/about/that.html' ) ).to eq '/how/about/that/'
end
it "returns a resource url when asset_hash is on" do
Given.fixture 'asset-hash-app'
@mm = Middleman::Application.new
expect( Middleman::Util.asset_url( @mm, '100px.png', 'images') ).to match %r|/images/100px-[a-f0-9]+.png|
end
end
describe "::find_related_files" do
after(:each) do
Given.cleanup!
end
before(:each) do
Given.fixture 'related-files-app'
@mm = Middleman::Application.new
end
def source_file(path)
Pathname(File.expand_path("source/#{path}"))
end
it "Finds partials possibly related to ERb files" do
related = Middleman::Util.find_related_files(@mm, [source_file('partials/_test.erb')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/index.html.erb")
related = Middleman::Util.find_related_files(@mm, [source_file('partials/_test2.haml')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/index.html.erb")
end
it "Finds partials possible related to Scss files" do
related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/_include4.scss')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/stylesheets/site.css.scss")
expect(related).to include File.expand_path("source/stylesheets/include2.css.scss")
related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/include2.css.scss')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/stylesheets/site.css.scss")
expect(related).not_to include File.expand_path("source/stylesheets/include2.css.scss")
related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/include1.css')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/stylesheets/site.css.scss")
expect(related).to include File.expand_path("source/stylesheets/include2.css.scss")
related = Middleman::Util.find_related_files(@mm, [source_file('stylesheets/_include3.sass')]).map { |f| f[:full_path].to_s }
expect(related).to include File.expand_path("source/stylesheets/site.css.scss")
expect(related).to include File.expand_path("source/stylesheets/include2.css.scss")
end
end
describe "::step_through_extensions" do
it "returns the base name after templating engine extensions are removed" do
result = Middleman::Util.step_through_extensions('my_file.html.haml.erb')
expect(result).to eq 'my_file.html'
end
it "does not loop infinitely when file name is a possible templating engine" do
expect do
Timeout::timeout(3.0) do
result = Middleman::Util.step_through_extensions("markdown.scss")
expect(result).to eq "markdown"
end
end.not_to raise_error
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/core_extensions/data_spec.rb | middleman-core/spec/middleman-core/core_extensions/data_spec.rb | require 'spec_helper'
require 'middleman-core/core_extensions'
require 'middleman-core/core_extensions/data'
describe Middleman::CoreExtensions::Data do
end
describe Middleman::CoreExtensions::Data::DataStore do
describe "#store" do
before :each do
@subject = described_class.new instance_double("Middleman::Application"),
Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
end
context "when given a name and data" do
it "adds data at the given name" do
@subject.store :foo, { 'bar' => 'baz' }
@subject.store :baz, [:wu, :tang]
expect( @subject.store['foo'] ).to eq({ 'bar' => 'baz' })
expect( @subject.store['baz'] ).to match_array [:wu, :tang]
end
it "overwrites previous keys if given the same key" do
@subject.store :foo, { 'bar' => 'baz' }
@subject.store :foo, [:wu, :tang]
expect( @subject.store['foo'] ).to match_array [:wu, :tang]
end
end
context "when given no args" do
it "returns @local_sources instance var" do
@subject.instance_variable_set :"@local_sources", { foo: 'bar' }
expect( @subject.store ).to eq({ foo: 'bar' })
end
end
end
describe "#callbacks" do
before :each do
@subject = described_class.new instance_double("Middleman::Application"),
Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
end
context "when given a name and proc" do
it "adds a callback at the given name" do
@subject.callbacks :foo, lambda { "bar" }
callback = @subject.instance_variable_get(:@callback_sources)['foo']
expect( callback.call ).to eq "bar"
end
it "overwrites previous keys if given the same key" do
@subject.callbacks :foo, lambda { "bar" }
@subject.callbacks :foo, lambda { "baz" }
callback = @subject.instance_variable_get(:@callback_sources)['foo']
expect( callback.call ).to eq "baz"
end
end
context "when given no args" do
it "returns @callback_sources instance var" do
@subject.instance_variable_set :"@callback_sources", { foo: 'bar' }
expect( @subject.callbacks ).to eq({ foo: 'bar' })
end
end
end
describe "#data_for_path" do
before :each do
@subject = described_class.new instance_double("Middleman::Application"),
Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
end
context "given path matches local data" do
it "returns hash for key" do
@subject.store :foo, { 'bar' => 'baz' }
expect( @subject.data_for_path(:foo) ).to eq({ 'bar' => 'baz' })
end
it "returns array for key" do
@subject.store :foo, [:bar, :baz]
expect( @subject.data_for_path(:foo) ).to match_array [:bar, :baz]
end
end
context "given path matches callback data" do
it "returns value of calback lambda" do
@subject.callbacks :foo, lambda { { 'bar' => 'baz' } }
@subject.callbacks :wu, lambda { [:tang, :clan] }
expect( @subject.data_for_path(:foo) ).to eq({ 'bar' => 'baz' })
expect( @subject.data_for_path(:wu) ).to match_array [:tang, :clan]
end
end
context "given path matches both sources" do
it "returns match from local data" do
@subject.store :foo, { 'local' => 'data' }
@subject.callbacks :foo, lambda { { 'callback' => 'data' } }
expect( @subject.data_for_path(:foo) ).to eq({ 'local' => 'data' })
end
end
context "given path matches no sources" do
it "returns nil" do
expect( @subject.data_for_path(:missing) ).to be_nil
end
end
end
describe "#key?" do
it "returns true if key included in local_data, local_sources, or callback_sources" do
subject = described_class.new instance_double("Middleman::Application"), Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
subject.store :"foo-store", { foo: "bar" }
subject.callbacks :"foo-callback", Proc.new { "bar" }
subject.instance_variable_get(:@local_data)["foo-local"] = "bar"
expect( subject.key?("foo-store") ).to be_truthy
expect( subject.key?("foo-callback") ).to be_truthy
expect( subject.key?("foo-local") ).to be_truthy
end
it "returns false if key not in local_data, local_sources, or callback_sources" do
subject = described_class.new instance_double("Middleman::Application"), Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
expect( subject.key?("foo-store") ).to be_falsy
expect( subject.key?("foo-callback") ).to be_falsy
expect( subject.key?("foo-local") ).to be_falsy
end
it "doesn't raise a stack error if missing the given key" do
subject = described_class.new instance_double("Middleman::Application"), Middleman::CoreExtensions::Data::DATA_FILE_MATCHER
expect{
subject.respond_to? :test
}.not_to raise_error
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/preview_server/server_ip_address_spec.rb | middleman-core/spec/middleman-core/preview_server/server_ip_address_spec.rb | require 'spec_helper'
require 'middleman-core/preview_server/server_ip_address'
RSpec.describe Middleman::PreviewServer::ServerIpAddress do
subject(:ip_address) { described_class.new(string) }
let(:string) { '127.0.0.1' }
describe '#to_s' do
context 'when ipv4' do
let(:string) { '127.0.0.1' }
it { expect(ip_address.to_s).to eq string }
end
context 'when ipv6' do
context 'without suffix' do
let(:string) { '2607:f700:8000:12e:b3d9:1cba:b52:aa1b' }
it { expect(ip_address.to_s).to eq string }
end
context 'with suffix' do
let(:string) { '2607:f700:8000:12e:b3d9:1cba:b52:aa1b%wlp1s0' }
let(:result) { '2607:f700:8000:12e:b3d9:1cba:b52:aa1b' }
it { expect(ip_address.to_s).to eq result }
end
end
end
describe '#to_browser' do
context 'when ip_address' do
it { expect(ip_address.to_browser).to eq string }
end
context 'when ipv4' do
let(:string) { '127.0.0.1' }
it { expect(ip_address.to_browser).to eq string }
end
context 'when ipv6' do
let(:string) { '2607:f700:8000:12e:b3d9:1cba:b52:aa1b' }
it { expect(ip_address.to_browser).to eq "[#{string}]" }
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/spec/middleman-core/preview_server/server_hostname_spec.rb | middleman-core/spec/middleman-core/preview_server/server_hostname_spec.rb | require 'spec_helper'
require 'middleman-core/preview_server/server_hostname'
RSpec.describe Middleman::PreviewServer::ServerHostname do
subject(:hostname) { described_class.new(string) }
let(:string) { 'www.example.com' }
describe '#to_s' do
context 'when hostname' do
it { expect(hostname.to_s).to eq string }
end
context 'when ipv4' do
let(:string) { '127.0.0.1' }
it { expect(hostname.to_s).to eq string }
end
context 'when ipv6' do
let(:string) { '2607:f700:8000:12e:b3d9:1cba:b52:aa1b' }
it { expect(hostname.to_s).to eq string }
end
end
describe '#to_browser' do
context 'when hostname' do
it { expect(hostname.to_browser).to eq string }
end
context 'when ipv4' do
let(:string) { '127.0.0.1' }
it { expect(hostname.to_browser).to eq string }
end
context 'when ipv6' do
let(:string) { '::1' }
it { expect(hostname.to_browser).to eq string }
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core.rb | middleman-core/lib/middleman-core.rb | # Setup our load paths
libdir = File.expand_path(File.dirname(__FILE__))
$LOAD_PATH.unshift(libdir) unless $LOAD_PATH.include?(libdir)
# Top-level Middleman namespace
module Middleman
autoload :Application, 'middleman-core/application'
end
require 'middleman-core/version'
require 'middleman-core/util'
require 'middleman-core/extensions'
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman/rack.rb | middleman-core/lib/middleman/rack.rb | require 'middleman-core/load_paths'
::Middleman.setup_load_paths
require 'middleman-core'
require 'middleman-core/rack'
require 'middleman-core/application'
module Middleman
def self.server
::Middleman::Rack.new(::Middleman::Application.new)
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/template_context.rb | middleman-core/lib/middleman-core/template_context.rb | require 'pathname'
require 'middleman-core/file_renderer'
require 'middleman-core/template_renderer'
require 'middleman-core/contracts'
module Middleman
# The TemplateContext Class
#
# A clean context, separate from Application, in which templates can be executed.
# All helper methods and values available in a template, but be accessible here.
# Also implements two helpers: wrap_layout & render (used by padrino's partial method).
# A new context is created for each render of a path, but that context is shared through
# the request, passed from template, to layouts and partials.
class TemplateContext
extend Forwardable
include Contracts
# Allow templates to directly access the current app instance.
# @return [Middleman::Application]
attr_reader :app
# Required for Padrino's rendering
attr_accessor :current_engine
# Shorthand references to global values on the app instance.
def_delegators :@app, :config, :logger, :sitemap, :server?, :build?, :environment?, :environment, :data, :extensions, :root, :development?, :production?
# Initialize a context with the current app and predefined locals and options hashes.
#
# @param [Middleman::Application] app
# @param [Hash] locs
# @param [Hash] opts
def initialize(app, locs={}, opts={})
@app = app
@locs = locs
@opts = opts
end
# Return the current buffer to the caller and clear the value internally.
# Used when moving between templates when rendering layouts or partials.
#
# @api private
# @return [String] The old buffer.
def save_buffer
@_out_buf, buf_was = '', @_out_buf
buf_was
end
# Restore a previously saved buffer.
#
# @api private
# @param [String] buf_was
# @return [void]
def restore_buffer(buf_was)
@_out_buf = buf_was
end
# Allow layouts to be wrapped in the contents of other layouts.
#
# @param [String, Symbol] layout_name
# @return [void]
def wrap_layout(layout_name, &block)
# Save current buffer for later
buf_was = save_buffer
# Find a layout for this file
layout_file = ::Middleman::TemplateRenderer.locate_layout(@app, layout_name, current_engine)
# Get the layout engine
extension = File.extname(layout_file[:relative_path])
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
self.current_engine = engine
engine_was = current_engine
# By default, no content is captured
content = ''
# Attempt to capture HTML from block
begin
content = capture_html(&block) if block_given?
ensure
# Reset stored buffer, regardless of success
restore_buffer(buf_was)
end
# Render the layout, with the contents of the block inside.
concat_safe_content render_file(layout_file, @locs, @opts) { content }
ensure
# Reset engine back to template's value, regardless of success
self.current_engine = engine_was
end
# Sinatra/Padrino compatible render method signature referenced by some view
# helpers. Especially partials.
#
# @param [String, Symbol] name The partial to render.
# @param [Hash] options
# @param [Proc] block A block will be evaluated to return internal contents.
# @return [String]
Contract Any, Or[Symbol, String], Hash, Hash, Maybe[Proc] => String
def render(_, name, options={}, locals={}, &block)
name = name.to_s
partial_file = locate_partial(name, false) || locate_partial(name, true)
raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate partial: #{name}" unless partial_file
source_path = sitemap.file_to_path(partial_file)
r = sitemap.find_resource_by_path(source_path)
if (r && !r.template?) || (Tilt[partial_file[:full_path]].nil? && partial_file[:full_path].exist?)
partial_file.read
else
opts = options.dup
locs = locals.dup
render_file(partial_file, locs, opts, &block)
end
end
# Locate a partial relative to the current path or the source dir, given a partial's path.
#
# @api private
# @param [String] partial_path
# @return [String]
Contract String, Maybe[Bool] => Maybe[IsA['Middleman::SourceFile']]
def locate_partial(partial_path, try_static=true)
partial_file = nil
lookup_stack = []
non_root = partial_path.to_s.sub(/^\//, '')
non_root_no_underscore = non_root.sub(/^_/, '').sub(/\/_/, '/')
if resource = current_resource
current_dir = resource.file_descriptor[:relative_path].dirname
relative_dir = current_dir + Pathname(non_root)
relative_dir_no_underscore = current_dir + Pathname(non_root_no_underscore)
end
if relative_dir
lookup_stack.push [relative_dir.to_s,
{ preferred_engine: resource.file_descriptor[:relative_path]
.extname[1..-1].to_sym }]
end
lookup_stack.push [non_root]
lookup_stack.push [non_root,
{ try_static: try_static }]
if relative_dir_no_underscore
lookup_stack.push [relative_dir_no_underscore.to_s,
{ try_static: try_static }]
end
lookup_stack.push [non_root_no_underscore,
{ try_static: try_static }]
lookup_stack.each do |args|
partial_file = ::Middleman::TemplateRenderer.resolve_template(@app, *args)
break if partial_file
end
partial_file
end
def current_path
@locs[:current_path]
end
# Get the resource object for the current path
# @return [Middleman::Sitemap::Resource]
def current_resource
return nil unless current_path
sitemap.find_resource_by_destination_path(current_path)
end
alias current_page current_resource
protected
# Render a path with locs, opts and contents block.
#
# @api private
# @param [Middleman::SourceFile] file The file.
# @param [Hash] locs Template locals.
# @param [Hash] opts Template options.
# @param [Proc] block A block will be evaluated to return internal contents.
# @return [String] The resulting content string.
Contract IsA['Middleman::SourceFile'], Hash, Hash, Maybe[Proc] => String
def render_file(file, locs, opts, &block)
_render_with_all_renderers(file[:relative_path].to_s, locs, self, opts, &block)
end
Contract String, Hash, Any, Hash, Maybe[Proc] => String
def _render_with_all_renderers(path, locs, context, opts, &block)
# Keep rendering template until we've used up all extensions. This
# handles cases like `style.css.sass.erb`
content = nil
while ::Middleman::Util.tilt_class(path)
begin
opts[:template_body] = content if content
content_renderer = ::Middleman::FileRenderer.new(@app, path)
content = content_renderer.render(locs, opts, context, &block)
path = File.basename(path, File.extname(path))
rescue LocalJumpError
raise "Tried to render a layout (calls yield) at #{path} like it was a template. Non-default layouts need to be in #{@app.config[:source]}/#{@app.config[:layouts_dir]}."
end
end
content
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extension_manager.rb | middleman-core/lib/middleman-core/extension_manager.rb | module Middleman
class ExtensionManager
extend Forwardable
def_delegator :@app, :logger
def_delegators :@activated, :[], :each
def initialize(app)
@app = app
@activated = {}
::Middleman::Extensions.load_settings(@app)
manager = self
{
before_sitemap: :before_sitemap,
initialized: :before_configuration
}.each do |key, value|
cb = proc { manager.auto_activate(value) }
@app.send(key, &cb)
end
@app.after_configuration_eval(&method(:activate_all))
end
def auto_activate(key)
::Middleman::Extensions.auto_activate(key, @app)
end
# Activate an extension, optionally passing in options.
# This method is typically used from a project's `config.rb`.
#
# @example Activate an extension with no options
# activate :lorem
#
# @example Activate an extension, with options
# activate :minify_javascript, inline: true
#
# @example Use a block to configure extension options
# activate :minify_javascript do |opts|
# opts.ignore += ['*-test.js']
# end
#
# @param [Symbol] ext_name The name of thed extension to activate
# @param [Hash] options Options to pass to the extension
# @yield [Middleman::Configuration::ConfigurationManager] Extension options that can be modified before the extension is initialized.
# @return [void]
def activate(ext_name, options={}, &block)
begin
extension = ::Middleman::Extensions.load(ext_name)
rescue LoadError => e
logger.debug "== Failed Activation `#{ext_name}` : #{e.message}"
return
end
logger.debug "== Activating: #{ext_name}"
if extension.supports_multiple_instances?
@activated[ext_name] ||= {}
key = "instance_#{@activated[ext_name].keys.length}"
@activated[ext_name][key] = extension.new(@app, options, &block)
elsif @activated.key?(ext_name)
raise "#{ext_name} has already been activated and cannot be re-activated."
else
@activated[ext_name] = extension.new(@app, options, &block)
end
end
def activate_all
logger.debug 'Loaded extensions:'
@instances = @activated.each_with_object([]) do |(ext_name, ext), sum|
if ext.is_a?(Hash)
ext.each do |instance_key, instance|
logger.debug "== Extension: #{ext_name} #{instance_key}"
sum << instance
end
else
logger.debug "== Extension: #{ext_name}"
sum << ext
end
end
@instances.each do |ext|
::Middleman::Extension.activated_extension(ext)
end
end
def add_exposed_to_context(context)
@instances.each do |ext|
ext.add_exposed_to_context(context)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/version.rb | middleman-core/lib/middleman-core/version.rb | module Middleman
# Current Version
# @return [String]
VERSION = '4.6.2'.freeze unless const_defined?(:VERSION)
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/profiling.rb | middleman-core/lib/middleman-core/profiling.rb | module Middleman
module Profiling
class << self
# The profiler instance. There can only be one!
attr_writer :profiler
def profiler
@profiler ||= NullProfiler.new
end
# Start the profiler
def start
profiler.start
end
# Stop the profiler and generate a report. Make sure to call start first
def report(report_name)
profiler.report(report_name)
end
end
# A profiler that does nothing. The default.
class NullProfiler
def start; end
def report(_); end
end
# A profiler that uses ruby-prof
class RubyProfProfiler
def initialize
require 'ruby-prof'
rescue LoadError
raise "To use the --profile option, you must add the 'ruby-prof' gem to your Gemfile"
end
def start
RubyProf.start
end
def report(report_name)
result = RubyProf.stop
printer = RubyProf::GraphHtmlPrinter.new(result)
outfile = File.join('profile', report_name)
outfile = (outfile + '.html') unless outfile.end_with? '.html'
FileUtils.mkdir_p(File.dirname(outfile))
File.open(outfile, 'w') do |f|
printer.print(f, min_percent: 1)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sources.rb | middleman-core/lib/middleman-core/sources.rb | require 'hamster'
require 'middleman-core/contracts'
module Middleman
# The standard "record" that contains information about a file on disk.
SourceFile = Struct.new(:relative_path, :full_path, :directory, :types, :version) do
def read
::Middleman::Sources.file_cache[full_path] ||= {}
::Middleman::Sources.file_cache[full_path][version] ||= ::File.read(full_path)
end
def normalized_relative_path
@normalized_relative_path ||= ::Middleman::Util.normalize_path relative_path.to_s
end
end
# Sources handle multiple on-disk collections of files which make up
# a Middleman project. They are separated by `type` which can then be
# queried. For example, the `source` type represents all content that
# the sitemap uses to build a project. The `data` type represents YAML
# data. The `locales` type represents localization YAML, and so on.
class Sources
extend Forwardable
include Contracts
# Types which could cause output to change.
OUTPUT_TYPES = [:source, :locales, :data].freeze
# Types which require a reload to eval ruby
CODE_TYPES = [:reload].freeze
Matcher = Or[Regexp, RespondTo[:call]]
# A reference to the current app.
Contract IsA['Middleman::Application']
attr_reader :app
# Duck-typed definition of a valid source watcher
HANDLER = RespondTo[:on_change]
# Config
Contract Hash
attr_reader :options
# Reference to the global logger.
def_delegator :@app, :logger
cattr_accessor :file_cache
# Built-in types
# :source, :data, :locales, :reload
# Create a new collection of sources.
#
# @param [Middleman::Application] app The parent app.
# @param [Hash] options Global options.
# @param [Array] watchers Default watchers.
Contract IsA['Middleman::Application'], Maybe[Hash], Maybe[Array] => Any
def initialize(app, _options={}, watchers=[])
@app = app
@watchers = watchers
@sorted_watchers = @watchers.dup.freeze
::Middleman::Sources.file_cache = {}
# Set of procs wanting to be notified of changes
@on_change_callbacks = ::Hamster::Vector.empty
# Global ignores
@ignores = ::Hamster::Hash.empty
# Whether we're "running", which means we're in a stable
# watch state after all initialization and config.
@running = false
@update_count = 0
@last_update_count = -1
# When the app is about to shut down, stop our watchers.
@app.before_shutdown(&method(:stop!))
end
# Add a proc to ignore paths with either a regex or block.
#
# @param [Symbol] name A name for the ignore.
# @param [Symbol] type The type of content to apply the ignore to.
# @param [Regexp] regex Ignore by path regex.
# @param [Proc] block Ignore by block evaluation.
# @return [void]
Contract Symbol, Symbol, Or[Regexp, Proc] => Any
def ignore(name, type, regex=nil, &block)
@ignores = @ignores.put(name, type: type,
validator: (block_given? ? block : regex))
bump_count
poll_once! if @running
end
# Whether this path is ignored.
#
# @param [Middleman::SourceFile] file The file to check.
# @return [Boolean]
Contract SourceFile => Bool
def globally_ignored?(file)
@ignores.values.any? do |descriptor|
((descriptor[:type] == :all) || file[:types].include?(descriptor[:type])) &&
matches?(descriptor[:validator], file)
end
end
# Connect a new watcher. Can either be a type with options, which will
# create a `SourceWatcher` or you can pass in an instantiated class which
# responds to #changed and #deleted
#
# @param [Symbol, #changed, #deleted] type_or_handler The handler.
# @param [Hash] options The watcher options.
# @return [#changed, #deleted]
Contract Or[Symbol, HANDLER], Maybe[Hash] => HANDLER
def watch(type_or_handler, options={})
handler = if type_or_handler.is_a? Symbol
path = File.expand_path(options.delete(:path), app.root)
SourceWatcher.new(self, type_or_handler, path, options)
else
type_or_handler
end
@watchers << handler
# The index trick is used so that the sort is stable - watchers with the same priority
# will always be ordered in the same order as they were registered.
n = 0
@sorted_watchers = @watchers.sort_by do |w|
priority = w.options.fetch(:priority, 50)
n += 1
[priority, n]
end.reverse.freeze
handler.on_change(&method(:did_change))
if @running
handler.poll_once!
handler.listen!
end
handler
end
# A list of registered watchers
Contract ArrayOf[HANDLER]
def watchers
@sorted_watchers
end
# Disconnect a specific watcher.
#
# @param [SourceWatcher] watcher The watcher to remove.
# @return [void]
Contract RespondTo[:on_change] => Any
def unwatch(watcher)
@watchers.delete(watcher)
watcher.unwatch
bump_count
end
# Filter the collection of watchers by a type.
#
# @param [Symbol] type The watcher type.
# @return [Middleman::Sources]
Contract Symbol => ::Middleman::Sources
def by_type(type)
self.class.new @app, nil, watchers.select { |d| d.type == type }
end
# Get all files for this collection of watchers.
#
# @return [Array<Middleman::SourceFile>]
Contract ArrayOf[SourceFile]
def files
watchers.flat_map(&:files).uniq { |f| f[:relative_path] }
end
# Find a file given a type and path.
#
# @param [Symbol,Array<Symbol>] types A list of file "type".
# @param [String] path The file path.
# @param [Boolean] glob If the path contains wildcard or glob characters.
# @return [Middleman::SourceFile, nil]
Contract Or[Symbol, ArrayOf[Symbol], SetOf[Symbol]], Or[Pathname, String], Maybe[Bool] => Maybe[SourceFile]
def find(types, path, glob=false)
array_of_types = Array(types)
watchers
.lazy
.select { |d| array_of_types.include?(d.type) }
.map { |d| d.find(path, glob) }
.reject(&:nil?)
.first
end
# Check if a file for a given type exists.
#
# @param [Symbol,Array<Symbol>] types The list of file "type".
# @param [String] path The file path relative to it's source root.
# @return [Boolean]
Contract Or[Symbol, ArrayOf[Symbol], SetOf[Symbol]], String => Bool
def exists?(types, path)
watchers.any? { |d| Array(types).include?(d.type) && d.exists?(path) }
end
# Check if a file for a given type exists.
#
# @param [Symbol,Array<Symbol>] types The list of file "type".
# @param [String] path The file path relative to it's source root.
# @return [Boolean]
Contract Or[Symbol, ArrayOf[Symbol], SetOf[Symbol]], String => Maybe[HANDLER]
def watcher_for_path(types, path)
watchers.detect { |d| Array(types).include?(d.type) && d.exists?(path) }
end
# Manually check for new files
#
# @return [void]
Contract ArrayOf[Pathname]
def find_new_files!
return [] unless @update_count != @last_update_count
@last_update_count = @update_count
watchers.reduce([]) { |sum, w| sum + w.find_new_files! }
end
# Manually poll all watchers for new content.
#
# @return [void]
Contract ArrayOf[Pathname]
def poll_once!
return [] unless @update_count != @last_update_count
@last_update_count = @update_count
watchers.reduce([]) { |sum, w| sum + w.poll_once! }
end
# Start up all listeners.
#
# @return [void]
Contract Any
def start!
watchers.each(&:listen!)
@running = true
end
# Stop the watchers.
#
# @return [void]
Contract Any
def stop!
watchers.each(&:stop_listener!)
@running = false
end
# A callback requires a type and the proc to execute.
CallbackDescriptor = Struct.new :type, :proc
# Add callback to be run on file change or deletion
#
# @param [Symbol,Array<Symbol>] types The change types to register the callback.
# @return [void]
Contract Or[Symbol, ArrayOf[Symbol], SetOf[Symbol]], Proc => Any
def on_change(types, &block)
Array(types).each do |type|
@on_change_callbacks = @on_change_callbacks.push(CallbackDescriptor.new(type, block))
end
end
# Backwards compatible change handler.
#
# @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any
def changed(matcher=nil, &_block)
on_change OUTPUT_TYPES do |updated, _removed|
updated
.select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| yield f[:relative_path] }
end
end
# Backwards compatible delete handler.
#
# @param [nil,Regexp] matcher A Regexp to match the change path against
Contract Maybe[Matcher] => Any
def deleted(matcher=nil, &_block)
on_change OUTPUT_TYPES do |_updated, removed|
removed
.select { |f| matcher.nil? ? true : matches?(matcher, f) }
.each { |f| yield f[:relative_path] }
end
end
# Backwards compatible ignored check.
#
# @param [Pathname,String] path The path to check.
Contract Or[Pathname, String] => Bool
def ignored?(path)
descriptor = find(OUTPUT_TYPES, path)
!descriptor || globally_ignored?(descriptor)
end
protected
# Whether a validator matches a file.
#
# @param [Regexp, #call] validator The match validator.
# @param [Middleman::SourceFile] file The file to check.
# @return [Boolean]
Contract Matcher, SourceFile => Bool
def matches?(validator, file)
path = file[:relative_path]
if validator.is_a? Regexp
!!(path.to_s =~ validator)
else
!!validator.call(path, @app)
end
end
# Increment the internal counter for changes.
#
# @return [void]
Contract Any
def bump_count
@update_count += 1
end
# Notify callbacks that a file changed
#
# @param [Middleman::SourceFile] file The file that changed
# @return [void]
Contract ArrayOf[SourceFile], ArrayOf[SourceFile], HANDLER => Any
def did_change(updated_files, removed_files, watcher)
valid_updated = updated_files.select do |file|
watcher_for_path(file[:types], file[:relative_path].to_s) == watcher
end
valid_removed = removed_files.select do |file|
watcher_for_path(file[:types], file[:relative_path].to_s).nil?
end
return if valid_updated.empty? && valid_removed.empty?
bump_count
run_callbacks(@on_change_callbacks, valid_updated, valid_removed)
end
# Notify callbacks for a file given a set of callbacks
#
# @param [Set] callback_descriptors The registered callbacks.
# @param [Array<Middleman::SourceFile>] files The files that were changed.
# @return [void]
Contract VectorOf[CallbackDescriptor], ArrayOf[SourceFile], ArrayOf[SourceFile] => Any
def run_callbacks(callback_descriptors, updated_files, removed_files)
callback_descriptors.each do |callback|
if callback[:type] == :all
callback[:proc].call(updated_files, removed_files)
else
valid_updated = updated_files.select { |f| f[:types].include?(callback[:type]) }
valid_removed = removed_files.select { |f| f[:types].include?(callback[:type]) }
callback[:proc].call(valid_updated, valid_removed) unless valid_updated.empty? && valid_removed.empty?
end
end
end
end
end
# And, require the actual default implementation for a watcher.
require 'middleman-core/sources/source_watcher'
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/meta_pages.rb | middleman-core/lib/middleman-core/meta_pages.rb | require 'rack/builder'
require 'rack/static'
require 'tilt'
require 'middleman-core/meta_pages/sitemap_tree'
require 'middleman-core/meta_pages/config_setting'
module Middleman
module MetaPages
# Metadata pages to be served in preview, in order to present information about the Middleman
# application and its configuration. Analogous to Firefox/Chrome's "about:" pages.
#
# Built using a ghetto little Rack web framework cobbled together because I didn't want to depend
# on Sinatra or figure out how to host Middleman inside Middleman.
class Application
def initialize(middleman)
# Hold a reference to the middleman application
@middleman = middleman
meta_pages = self
@rack_app = ::Rack::Builder.new do
# Serve assets from metadata/assets
use ::Rack::Static, urls: ['/assets'], root: File.join(File.dirname(__FILE__), 'meta_pages')
map '/' do
run meta_pages.method(:index)
end
map '/sitemap' do
run meta_pages.method(:sitemap)
end
map '/config' do
run meta_pages.method(:config)
end
end
end
def call(*args)
@rack_app.call(*args)
end
# The index page
def index(_)
template('index.html.erb')
end
# Inspect the sitemap
def sitemap(_)
resources = @middleman.sitemap.resources(true)
sitemap_tree = SitemapTree.new
resources.each do |resource|
sitemap_tree.add_resource resource
end
template('sitemap.html.erb', sitemap_tree: sitemap_tree)
end
# Inspect configuration
def config(_)
global_config = @middleman.config.all_settings.map { |c| ConfigSetting.new(c) }
extension_config = {}
auto_activated_config = {}
@middleman.extensions.each do |ext_name, extension|
if ::Middleman::Extensions.auto_activated.include? ext_name
auto_activated_config[ext_name] = extension_options(extension)
next
end
if extension.is_a?(Hash)
# Multiple instance extension
if extension.size == 1
extension_config[ext_name] = extension_options(extension.values.first)
else
extension.each do |inst, ext|
extension_config["#{ext_name} (#{inst})"] = extension_options(ext)
end
end
else
extension_config[ext_name] = extension_options(extension)
end
end
template('config.html.erb',
global_config: global_config,
extension_config: extension_config,
auto_activated_config: auto_activated_config,
registered_extensions: Middleman::Extensions.registered.dup)
end
private
# Render a template with the given name and locals
def template(template_name, locals={})
template_path = File.join(File.dirname(__FILE__), 'meta_pages', 'templates', template_name)
content = Tilt.new(template_path).render(::Object.new, locals)
response(content)
end
# Respond to an HTML request
def response(content)
[200, { 'content-type' => 'text/html' }, Array(content)]
end
def extension_options(extension)
extension.options.all_settings.map { |c| ConfigSetting.new(c) }
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions.rb | middleman-core/lib/middleman-core/extensions.rb | require 'middleman-core/extension'
module Middleman
# The Extensions module is used to handle global registration and loading of Middleman Extensions.
#
# The application-facing extension API ({Middleman::CoreExtensions::Extensions#activate activate}, etc) is in {Middleman::CoreExtensions::Extensions} in
# `middleman-core/core_extensions/extensions.rb`.
module Extensions
@registered = {}
@auto_activate = {
# Activate before the Sitemap is instantiated
before_sitemap: Set.new,
# Activate the extension before `config.rb` and the `:before_configuration` hook.
before_configuration: Set.new
}
AutoActivation = Struct.new(:name, :modes)
class << self
# @api private
# A hash of all registered extensions. Registered extensions are not necessarily active - this
# is the set of all extensions that are known to Middleman.
# @return [Hash{Symbol => Class<Middleman::Extension>, Proc}] A directory of known extensions indexed by the name they were registered under. The value may be a Proc, which can be lazily called to return an extension class.
attr_reader :registered
# Register a new extension. Choose a name which will be
# used to activate the extension in `config.rb`, like this:
#
# activate :my_extension
#
# Provide your extension class either as the second parameter:
#
# Middleman::Extensions.register(:my_extension, MyExtension)
#
# Or better, return it from a block, which allows you to lazily require the implementation:
#
# Middleman::Extensions.register :my_extension do
# require 'my_extension'
# MyExtension
# end
#
# @param [Symbol] name The name of the extension
# @param [Class<Middleman::Extension>] extension_class The extension class (Must inherit from {Middleman::Extension})
# @option options [Boolean] :auto_activate If this is set to a lifecycle event (:before_configuration or :before_sitemap), this extension will be automatically activated at that point.
# This is intended for use with built-in Middleman extensions and should not be used by third-party extensions.
# @yield Instead of passing a module in namespace, you can provide
# a block which returns your extension class. This gives
# you the ability to require other files only when the
# extension is first activated.
# @return [void]
def register(name, extension_class=nil, options={}, &block)
raise 'Extension name must be a symbol' unless name.is_a?(Symbol)
# If we've already got an extension registered under this name, bail out
# raise "There is a already an extension registered with the name '#{name}'" if registered.key?(name)
# If the extension is defined with a block, grab options out of the "extension_class" parameter.
if extension_class && block_given? && options.empty? && extension_class.is_a?(Hash)
options = extension_class
extension_class = nil
end
registered[name] = if block_given?
block
elsif extension_class && extension_class.ancestors.include?(::Middleman::Extension)
extension_class
else
raise 'You must provide a Middleman::Extension or a block that returns a Middleman::Extension'
end
return unless options[:auto_activate]
descriptor = AutoActivation.new(name, options[:modes] || :all)
@auto_activate[options[:auto_activate]] << descriptor
end
# @api private
# Load an extension by name, lazily evaluating the block provided to {#register} if necessary.
# @param [Symbol] name The name of the extension
# @return [Class<Middleman::Extension>] A {Middleman::Extension} class implementing the extension
#
def load(name)
raise 'Extension name must be a symbol' unless name.is_a?(Symbol)
unless registered.key?(name)
raise "Unknown Extension: #{name}. Check the name and make sure you have referenced the extension's gem in your Gemfile."
end
extension_class = registered[name]
if extension_class.is_a?(Proc)
extension_class = extension_class.call
registered[name] = extension_class
end
unless extension_class.ancestors.include?(::Middleman::Extension)
raise "Tried to activate old-style extension: #{name}. They are no longer supported."
end
# Set the extension's name to whatever it was registered as.
extension_class.ext_name = name
extension_class
end
# @api private
# A flattened list of all extensions which are automatically activated
# @return [Array<Symbol>] A list of extension names which are automatically activated.
def auto_activated
@auto_activate.values.map(&:to_a).flatten.map(&:name)
end
# @api private
# Load autoactivatable extensions for the given env.
# @param [Symbol] group The name of the auto_activation group.
# @param [Middleman::Application] app An instance of the app.
def auto_activate(group, app)
@auto_activate[group].each do |descriptor|
next unless descriptor[:modes] == :all || descriptor[:modes].include?(app.config[:mode])
app.extensions.activate descriptor[:name]
end
end
def load_settings(app)
registered.each do |name, _|
begin
ext = load(name)
unless ext.global_config.all_settings.empty?
app.config.load_settings(ext.global_config.all_settings)
end
rescue LoadError
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/application.rb | middleman-core/lib/middleman-core/application.rb | require 'active_support/core_ext/integer/inflections'
require 'middleman-core/contracts'
require 'middleman-core/callback_manager'
require 'middleman-core/logger'
require 'middleman-core/sitemap/store'
require 'middleman-core/configuration'
require 'middleman-core/extension_manager'
require 'middleman-core/core_extensions'
require 'middleman-core/config_context'
require 'middleman-core/file_renderer'
require 'middleman-core/template_renderer'
# Core Middleman Class
module Middleman
MiddlewareDescriptor = Struct.new(:class, :options, :block)
MapDescriptor = Struct.new(:path, :block)
class Application
extend Forwardable
include Contracts
class << self
extend Forwardable
def_delegator :config, :define_setting
# Global configuration for the whole Middleman project.
# @return [ConfigurationManager]
def config
@config ||= ::Middleman::Configuration::ConfigurationManager.new
end
# Root project directory (overwritten in middleman build/server)
# @return [String]
def root
r = ENV['MM_ROOT'] ? ENV['MM_ROOT'].dup : ::Middleman::Util.current_directory
r.encode!('UTF-8', 'UTF-8-MAC') if RUBY_PLATFORM =~ /darwin/
r
end
# Pathname-addressed root
def root_path
Pathname(root)
end
end
Contract ::Middleman::ConfigContext
attr_reader :config_context
Contract ::Middleman::Sitemap::Store
attr_reader :sitemap
# An anonymous subclass of ::Middleman::TemplateContext
attr_reader :template_context_class
# An instance of the above anonymouse class.
attr_reader :generic_template_context
Contract ::Middleman::Configuration::ConfigurationManager
attr_reader :config
Contract ::Middleman::ExtensionManager
attr_reader :extensions
Contract SetOf[MiddlewareDescriptor]
attr_reader :middleware
Contract SetOf[MapDescriptor]
attr_reader :mappings
# Which port preview should start on.
# @return [Fixnum]
define_setting :port, 4567, 'The preview server port'
# Which server name should be used
# @return [NilClass, String]
define_setting :server_name, nil, 'The server name of preview server'
# Which bind address the preview server should use
# @return [NilClass, String]
define_setting :bind_address, nil, 'The bind address of the preview server'
# Whether to serve the preview server over HTTPS.
# @return [Boolean]
define_setting :https, false, 'Serve the preview server over SSL/TLS'
# The (optional) path to the SSL cert to use for the preview server.
# @return [String]
define_setting :ssl_certificate, nil, 'Path to an X.509 certificate to use for the preview server'
# The (optional) private key for the certificate in :ssl_certificate.
# @return [String]
define_setting :ssl_private_key, nil, "Path to an RSA private key for the preview server's certificate"
# Name of the source directory
# @return [String]
define_setting :source, 'source', 'Name of the source directory'
# If we should not run the sitemap.
# @return [Boolean]
define_setting :disable_sitemap, false, 'If we should not run the sitemap.'
# If we should exit before ready event.
# @return [Boolean]
define_setting :exit_before_ready, false, 'If we should exit before ready event.'
# Middleman mode. Defaults to :server, set to :build by the build process
# @return [String]
define_setting :mode, :server, 'Middleman mode. Defaults to :server'
# Middleman environment. Defaults to :development
# @return [String]
define_setting :environment, ((ENV['MM_ENV'] && ENV['MM_ENV'].to_sym) || :development), 'Middleman environment. Defaults to :development', import: proc { |s| s.to_sym }
# Which file should be used for directory indexes
# @return [String]
define_setting :index_file, 'index.html', 'Which file should be used for directory indexes'
# Whether to strip the index file name off links to directory indexes
# @return [Boolean]
define_setting :strip_index_file, true, 'Whether to strip the index file name off links to directory indexes'
# Whether to include a trailing slash when stripping the index file
# @return [Boolean]
define_setting :trailing_slash, true, 'Whether to include a trailing slash when stripping the index file'
# Location of javascripts within source.
# @return [String]
define_setting :js_dir, 'javascripts', 'Location of javascripts within source'
# Location of stylesheets within source.
# @return [String]
define_setting :css_dir, 'stylesheets', 'Location of stylesheets within source'
# Location of images within source. Used by HTML helpers.
# @return [String]
define_setting :images_dir, 'images', 'Location of images within source'
# Location of fonts within source.
# @return [String]
define_setting :fonts_dir, 'fonts', 'Location of fonts within source'
# Location of layouts within source. Used by renderers.
# @return [String]
define_setting :layouts_dir, 'layouts', 'Location of layouts within source'
# Where to build output files
# @return [String]
define_setting :build_dir, 'build', 'Where to build output files'
# Default prefix for building paths. Used by HTML helpers.
# @return [String]
define_setting :http_prefix, '/', 'Default prefix for building paths'
# Default layout name
# @return [String]
define_setting :layout, :_auto_layout, 'Default layout name'
# Which file extensions have a layout by default.
# @return [Array.<String>]
define_setting :extensions_with_layout, %w(.htm .html .xhtml .php), 'Which file extensions have a layout by default.'
# Which file extensions are "assets."
# @return [Array.<String>]
define_setting :asset_extensions, %w(.css .png .jpg .jpeg .webp .svg .svgz .js .gif .ttf .otf .woff .woff2 .eot .ico .map), 'Which file extensions are treated as assets.'
# Default string encoding for templates and output.
# @return [String]
define_setting :encoding, 'utf-8', 'Default string encoding for templates and output'
# Should Padrino include CRSF tag
# @return [Boolean]
define_setting :protect_from_csrf, false, 'Should Padrino include CRSF tag'
# Set to automatically convert some characters into a directory
define_setting :automatic_directory_matcher, nil, 'Set to automatically convert some characters into a directory'
# Setup callbacks which can exclude paths from the sitemap
define_setting :ignored_sitemap_matchers, {
# Files starting with an underscore, but not a double-underscore
partials: proc do |file|
ignored = false
file[:relative_path].ascend do |f|
if f.basename.to_s =~ %r{^_[^_]}
ignored = true
break
end
end
ignored
end,
layout: ->(file, app) {
file[:relative_path].to_s.start_with?('layout.', app.config[:layouts_dir] + '/')
}
}, 'Callbacks that can exclude paths from the sitemap'
define_setting :skip_build_clean, proc { |p| [/\.git/].any? { |r| p =~ r } }, 'Whether some paths should not be removed during a clean build.'
define_setting :cli_options, {}, 'Options from the Command Line.'
define_setting :watcher_disable, false, 'If the Listen watcher should not run'
define_setting :watcher_force_polling, false, 'If the Listen watcher should run in polling mode'
define_setting :watcher_latency, nil, 'The Listen watcher latency'
define_setting :watcher_wait_for_delay, 0.5, 'The Listen watcher delay between calls when changes exist'
# Delegate convenience methods off to their implementations
def_delegator :"::Middleman::Logger", :singleton, :logger
def_delegator :"::Middleman::Util", :instrument
def_delegators :"self.class", :root, :root_path
def_delegators :@generic_template_context, :link_to, :image_tag, :asset_path
def_delegators :@extensions, :activate
def_delegators :config, :define_setting
# Initialize the Middleman project
def initialize(&block)
# Search the root of the project for required files
$LOAD_PATH.unshift(root) unless $LOAD_PATH.include?(root)
::Middleman::Util.instrument 'application.setup' do
@callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [
:initialized,
:configure,
:before_extensions,
:before_instance_block,
:before_sitemap,
:before_configuration,
:after_configuration,
:after_configuration_eval,
:ready,
:before_build,
:after_build,
:before_shutdown,
:before, # Before Rack requests
:before_render,
:after_render,
:before_server,
:reload
])
@middleware = Set.new
@mappings = Set.new
@template_context_class = Class.new(Middleman::TemplateContext)
@generic_template_context = @template_context_class.new(self)
@config_context = ConfigContext.new(self, @template_context_class)
# Setup the default values from calls to set before initialization
@config = ::Middleman::Configuration::ConfigurationManager.new
@config.load_settings(self.class.config.all_settings)
config[:source] = ENV['MM_SOURCE'] if ENV['MM_SOURCE']
# TODO, make this less global
::Middleman::FileRenderer.cache.clear
::Middleman::TemplateRenderer.cache.clear
end
execute_callbacks(:before_extensions)
@extensions = ::Middleman::ExtensionManager.new(self)
execute_callbacks(:before_instance_block)
# Evaluate a passed block if given
config_context.instance_exec(&block) if block_given?
apply_cli_options
execute_callbacks(:before_sitemap)
# Initialize the Sitemap
@sitemap = ::Middleman::Sitemap::Store.new(self)
::Middleman::Extension.clear_after_extension_callbacks
# Before config is parsed, before extensions get to it.
execute_callbacks(:initialized)
# Before config is parsed. Mostly used for extensions.
execute_callbacks(:before_configuration)
# Eval config.
evaluate_configuration!
# Run any `configure` blocks for the current environment.
execute_callbacks([:configure, config[:environment]])
# Run any `configure` blocks for the current mode.
execute_callbacks([:configure, config[:mode]])
apply_cli_options
# Post parsing, pre-extension callback
execute_callbacks(:after_configuration_eval)
if Object.const_defined?(:Encoding)
Encoding.default_external = config[:encoding]
end
# After extensions have worked after_config
execute_callbacks(:after_configuration)
# Everything is stable
execute_callbacks(:ready) unless config[:exit_before_ready]
end
def apply_cli_options
config[:cli_options].each do |k, v|
setting = config.setting(k.to_sym)
next unless setting
v = setting.options[:import].call(v) if setting.options[:import]
config[k.to_sym] = v
end
end
# Eval config
def evaluate_configuration!
# Check for and evaluate local configuration in `config.rb`
config_rb = File.join(root, 'config.rb')
if File.exist? config_rb
logger.debug '== Reading: Local config: config.rb'
config_context.instance_eval File.read(config_rb), config_rb, 1
else
# Check for and evaluate local configuration in `middleman.rb`
middleman_rb = File.join(root, 'middleman.rb')
if File.exist? middleman_rb
logger.debug '== Reading: Local middleman: middleman.rb'
config_context.instance_eval File.read(middleman_rb), middleman_rb, 1
end
end
env_config = File.join(root, 'environments', "#{config[:environment]}.rb")
return unless File.exist? env_config
logger.debug "== Reading: #{config[:environment]} config"
config_context.instance_eval File.read(env_config), env_config, 1
end
# Whether we're in a specific mode
# @param [Symbol] key
# @return [Boolean]
Contract Symbol => Bool
def mode?(key)
config[:mode] == key
end
# Whether we're in server mode
# @return [Boolean] If we're in dev mode
Contract Bool
def server?
mode?(:server)
end
# Whether we're in build mode
# @return [Boolean] If we're in dev mode
Contract Bool
def build?
mode?(:build)
end
# Whether we're in a specific environment
# @param [Symbol] key
# @return [Boolean]
Contract Symbol => Bool
def environment?(key)
config[:environment] == key
end
# Backwards compatible helper. What the current environment is.
# @return [Symbol]
Contract Symbol
def environment
config[:environment]
end
# Backwards compatible helper. Whether we're in dev mode.
# @return [Boolean]
Contract Bool
def development?
environment?(:development)
end
# Backwards compatible helper. Whether we're in production mode.
# @return [Boolean]
Contract Bool
def production?
environment?(:production)
end
# Backwards compatible helper. The full path to the default source dir.
Contract Pathname
def source_dir
Pathname(File.join(root, config[:source]))
end
# Use Rack middleware
#
# @param [Class] middleware Middleware module
# @return [void]
# Contract Any, Args[Any], Maybe[Proc] => Any
def use(middleware, *args, &block)
@middleware << MiddlewareDescriptor.new(middleware, args, block)
end
# Add Rack App mapped to specific path
#
# @param [String] map Path to map
# @return [void]
Contract String, Proc => Any
def map(map, &block)
@mappings << MapDescriptor.new(map, block)
end
# Let everyone know we're shutting down.
def shutdown!
execute_callbacks(:before_shutdown)
end
# Set attributes (global variables)
#
# @deprecated Prefer accessing settings through "config".
#
# @param [Symbol] key Name of the attribue
# @param value Attribute value
# @return [void]
def set(key, value=nil, &block)
logger.warn "Warning: `set :#{key}` is deprecated. Use `config[:#{key}] =` instead."
value = block if block_given?
config[key] = value
end
# Work around this bug: http://bugs.ruby-lang.org/issues/4521
# where Ruby will call to_s/inspect while printing exception
# messages, which can take a long time (minutes at full CPU)
# if the object is huge or has cyclic references, like this.
def to_s
"#<Middleman::Application:0x#{object_id}>"
end
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/load_paths.rb | middleman-core/lib/middleman-core/load_paths.rb | # Core Pathname library used for traversal
require 'pathname'
module Middleman
class << self
def setup_load_paths
@_is_setup ||= begin
# Only look for config.rb if MM_ROOT isn't set
if !ENV['MM_ROOT'] && (found_path = findup('config.rb'))
ENV['MM_ROOT'] = found_path
end
# If we've found the root, try to setup Bundler
setup_bundler if ENV['MM_ROOT']
true
end
end
private
# Set BUNDLE_GEMFILE and run Bundler setup. Raises an exception if there is no Gemfile
def setup_bundler
if found_gemfile_root = findup('Gemfile', ENV['MM_ROOT'])
ENV['BUNDLE_GEMFILE'] ||= File.join(found_gemfile_root, 'Gemfile')
end
unless File.exist?(ENV['BUNDLE_GEMFILE'])
ENV['BUNDLE_GEMFILE'] = File.expand_path('../../../../Gemfile', __FILE__)
end
if File.exist?(ENV['BUNDLE_GEMFILE'])
require 'bundler/setup'
Bundler.require
else
raise "Couldn't find your Gemfile. Middleman projects require a Gemfile for specifying dependencies."
end
end
# Recursive method to find a file in parent directories
def findup(filename, cwd=Dir.pwd)
cwd = Pathname(cwd)
return cwd.to_s if (cwd + filename).exist?
return false if cwd.root?
findup(filename, cwd.parent)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions.rb | middleman-core/lib/middleman-core/core_extensions.rb | require 'middleman-core/extensions'
# File Change Notifier
Middleman::Extensions.register :file_watcher, auto_activate: :before_sitemap do
require 'middleman-core/core_extensions/file_watcher'
Middleman::CoreExtensions::FileWatcher
end
# Parse YAML from templates
Middleman::Extensions.register :front_matter, auto_activate: :before_sitemap do
require 'middleman-core/core_extensions/front_matter'
Middleman::CoreExtensions::FrontMatter
end
# Data looks at the data/ folder for YAML files and makes them available
# to dynamic requests.
Middleman::Extensions.register :data, auto_activate: :before_sitemap do
require 'middleman-core/core_extensions/data'
Middleman::CoreExtensions::Data
end
# Rewrite embedded URLs via Rack
Middleman::Extensions.register :inline_url_rewriter, auto_activate: :before_sitemap do
require 'middleman-core/core_extensions/inline_url_rewriter'
Middleman::CoreExtensions::InlineURLRewriter
end
# Catch and show exceptions at the Rack level
Middleman::Extensions.register :show_exceptions, auto_activate: :before_configuration, modes: [:server] do
require 'middleman-core/core_extensions/show_exceptions'
Middleman::CoreExtensions::ShowExceptions
end
# External helpers looks in the helpers/ folder for helper modules
Middleman::Extensions.register :external_helpers, auto_activate: :before_configuration do
require 'middleman-core/core_extensions/external_helpers'
Middleman::CoreExtensions::ExternalHelpers
end
# Extended version of Padrino's rendering
require 'middleman-core/core_extensions/rendering'
# Setup default helpers
Middleman::Extensions.register :default_helpers, auto_activate: :before_configuration do
require 'middleman-core/core_extensions/default_helpers'
Middleman::CoreExtensions::DefaultHelpers
end
# Lorem provides a handful of helpful prototyping methods to generate
# words, paragraphs, fake images, names and email addresses.
Middleman::Extensions.register :lorem, auto_activate: :before_configuration do
require 'middleman-core/extensions/lorem'
Middleman::Extensions::Lorem
end
Middleman::Extensions.register :routing, auto_activate: :before_configuration do
require 'middleman-core/core_extensions/routing'
Middleman::CoreExtensions::Routing
end
Middleman::Extensions.register :collections, auto_activate: :before_configuration do
require 'middleman-core/core_extensions/collections'
Middleman::CoreExtensions::Collections::CollectionsExtension
end
###
# Setup Optional Extensions
###
Middleman::Extensions.register :i18n do
require 'middleman-core/core_extensions/i18n'
Middleman::CoreExtensions::Internationalization
end
# CacheBuster adds a query string to assets in dynamic templates to
# avoid browser caches failing to update to your new content.
Middleman::Extensions.register :cache_buster do
require 'middleman-core/extensions/cache_buster'
Middleman::Extensions::CacheBuster
end
# RelativeAssets allow any asset path in dynamic templates to be either
# relative to the root of the project or use an absolute URL.
Middleman::Extensions.register :relative_assets do
require 'middleman-core/extensions/relative_assets'
Middleman::Extensions::RelativeAssets
end
# AssetHost allows you to setup multiple domains to host your static
# assets. Calls to asset paths in dynamic templates will then rotate
# through each of the asset servers to better spread the load.
Middleman::Extensions.register :asset_host do
require 'middleman-core/extensions/asset_host'
Middleman::Extensions::AssetHost
end
# MinifyCss compresses CSS
Middleman::Extensions.register :minify_css do
require 'middleman-core/extensions/minify_css'
Middleman::Extensions::MinifyCss
end
# MinifyJavascript compresses JS
Middleman::Extensions.register :minify_javascript do
require 'middleman-core/extensions/minify_javascript'
Middleman::Extensions::MinifyJavascript
end
# GZIP assets and pages during build
Middleman::Extensions.register :gzip do
require 'middleman-core/extensions/gzip'
Middleman::Extensions::Gzip
end
# AssetHash appends a hash of the file contents to the assets filename
# to avoid browser caches failing to update to your new content.
Middleman::Extensions.register :asset_hash do
require 'middleman-core/extensions/asset_hash'
Middleman::Extensions::AssetHash
end
# Provide Apache-style index.html files for directories
Middleman::Extensions.register :directory_indexes do
require 'middleman-core/extensions/directory_indexes'
Middleman::Extensions::DirectoryIndexes
end
# AutomaticImageSizes inspects the images used in your dynamic templates
# and automatically adds width and height attributes to their HTML
# elements.
Middleman::Extensions.register :automatic_image_sizes do
require 'middleman-core/extensions/automatic_image_sizes'
Middleman::Extensions::AutomaticImageSizes
end
# AutomaticAltTags uses the file name of the `image_tag` to generate
# a default `:alt` value.
Middleman::Extensions.register :automatic_alt_tags do
require 'middleman-core/extensions/automatic_alt_tags'
Middleman::Extensions::AutomaticAltTags
end
Middleman::Extensions.register :external_pipeline do
require 'middleman-core/extensions/external_pipeline'
Middleman::Extensions::ExternalPipeline
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/preview_server.rb | middleman-core/lib/middleman-core/preview_server.rb | require 'webrick'
require 'webrick/https'
require 'openssl'
require 'middleman-core/meta_pages'
require 'middleman-core/logger'
require 'middleman-core/rack'
require 'middleman-core/preview_server/server_information'
require 'middleman-core/preview_server/server_url'
require 'middleman-core/preview_server/server_information_callback_proxy'
module Middleman
class PreviewServer
class << self
extend Forwardable
attr_reader :app, :ssl_certificate, :ssl_private_key, :environment, :server_information
# Start an instance of Middleman::Application
# @return [void]
def start(opts={}, cli_options={})
# Do not buffer output, otherwise testing of output does not work
$stdout.sync = true
$stderr.sync = true
@options = opts
@cli_options = cli_options
@server_information = ServerInformation.new
@server_information.https = (@options[:https] == true)
# New app evaluates the middleman configuration. Since this can be
# invalid as well, we need to evaluate the configuration BEFORE
# checking for validity
the_app = initialize_new_app
# And now comes the check
unless server_information.valid?
$stderr.puts %(== Running Middleman failed: #{server_information.reason}. Please fix that and try again.)
exit 1
end
mount_instance(the_app)
app.logger.debug %(== Server information is provided by #{server_information.handler})
app.logger.debug %(== The Middleman is running in "#{environment}" environment)
app.logger.debug format('== The Middleman preview server is bound to %s', ServerUrl.new(hosts: server_information.listeners, port: server_information.port, https: server_information.https?).to_bind_addresses.join(', '))
app.logger.info format('== View your site at %s', ServerUrl.new(hosts: server_information.site_addresses, port: server_information.port, https: server_information.https?).to_urls.join(', '))
app.logger.info format('== Inspect your site configuration at %s', ServerUrl.new(hosts: server_information.site_addresses, port: server_information.port, https: server_information.https?).to_config_urls.join(', '))
@initialized ||= false
return if @initialized
@initialized = true
register_signal_handlers
# Save the last-used @options so it may be re-used when
# reloading later on.
::Middleman::Profiling.report('server_start')
app.execute_callbacks(:before_server, [ServerInformationCallbackProxy.new(server_information)])
if @options[:daemon]
# To output the child PID, let's make preview server a daemon by hand
if child_pid = fork
app.logger.info "== Middleman preview server is running in background with PID #{child_pid}"
Process.detach child_pid
exit 0
else
$stdout.reopen('/dev/null', 'w')
$stderr.reopen('/dev/null', 'w')
$stdin.reopen('/dev/null', 'r')
end
end
loop do
@webrick.start
# $mm_shutdown is set by the signal handler
if $mm_shutdown
shutdown
exit
elsif $mm_reload
$mm_reload = false
reload
end
end
end
# Detach the current Middleman::Application instance
# @return [void]
def stop
begin
app.logger.info '== The Middleman is shutting down'
rescue
# if the user closed their terminal STDOUT/STDERR won't exist
end
unmount_instance
end
# Simply stop, then start the server
# @return [void]
def reload
app.logger.info '== The Middleman is reloading'
app.execute_callbacks(:reload)
begin
app = initialize_new_app
rescue => e
$stderr.puts "Error reloading Middleman: #{e}\n#{e.backtrace.join("\n")}"
app.logger.info '== The Middleman is still running the application from before the error'
return
end
unmount_instance
@webrick.shutdown
@webrick = nil
mount_instance(app)
app.logger.info '== The Middleman has reloaded'
end
# Stop the current instance, exit Webrick
# @return [void]
def shutdown
stop
@webrick.shutdown
end
private
def initialize_new_app
opts = @options.dup
cli_options = @cli_options.dup
::Middleman::Logger.singleton(
opts[:debug] ? 0 : 1,
opts[:instrumenting] || false
)
app = ::Middleman::Application.new do
config[:cli_options] = cli_options.each_with_object({}) do |(k, v), sum|
sum[k] = v
end
ready do
unless config[:watcher_disable]
match_against = [
%r{^config\.rb$},
%r{^environments/[^\.](.*)\.rb$},
%r{^lib/[^\.](.*)\.rb$},
%r{^#{config[:helpers_dir]}/[^\.](.*)\.rb$}
]
# config.rb
watcher = files.watch :reload,
path: root,
only: match_against
# Hack around bower_components in root.
watcher.listener.ignore(/^bower_components/)
# Hack around node_modules in root.
watcher.listener.ignore(/^node_modules/)
# Hack around sass cache in root.
watcher.listener.ignore(/^\.sass-cache/)
# Hack around bundler cache in root.
watcher.listener.ignore(/^vendor\/bundle/)
end
end
end
# store configured port to make a check later on possible
configured_port = possible_from_cli(:port, app.config)
# Use configuration values to set `bind_address` etc. in
# `server_information`
server_information.use(bind_address: possible_from_cli(:bind_address, app.config),
port: possible_from_cli(:port, app.config),
server_name: possible_from_cli(:server_name, app.config),
https: possible_from_cli(:https, app.config))
app.logger.warn format('== The Middleman uses a different port "%s" then the configured one "%s" because some other server is listening on that port.', server_information.port, configured_port) unless server_information.port == configured_port
@environment = possible_from_cli(:environment, app.config)
@ssl_certificate = possible_from_cli(:ssl_certificate, app.config)
@ssl_private_key = possible_from_cli(:ssl_private_key, app.config)
app.files.on_change :reload do
$mm_reload = true
@webrick.stop
end
# Add in the meta pages application
meta_app = Middleman::MetaPages::Application.new(app)
app.map '/__middleman' do
run meta_app
end
app
end
def possible_from_cli(key, config)
if @cli_options[key]
@cli_options[key]
else
config[key]
end
end
# Trap some interupt signals and shut down smoothly
# @return [void]
def register_signal_handlers
%w(INT HUP TERM QUIT).each do |sig|
next unless Signal.list[sig]
Signal.trap(sig) do
# Do as little work as possible in the signal context
$mm_shutdown = true
@webrick.stop
end
end
end
# Initialize webrick
# @return [void]
def setup_webrick(is_logging)
http_opts = {
Port: server_information.port,
AccessLog: [],
ServerName: server_information.server_name,
BindAddress: server_information.bind_address.to_s,
DoNotReverseLookup: true
}
if server_information.https?
http_opts[:SSLEnable] = true
if ssl_certificate || ssl_private_key
raise 'You must provide both :ssl_certificate and :ssl_private_key' unless ssl_private_key && ssl_certificate
http_opts[:SSLCertificate] = OpenSSL::X509::Certificate.new ::File.read ssl_certificate
http_opts[:SSLPrivateKey] = OpenSSL::PKey::RSA.new ::File.read ssl_private_key
else
# use a generated self-signed cert
http_opts[:SSLCertName] = [
%w(CN localhost),
%w(CN #{host})
].uniq
cert, key = create_self_signed_cert(1024, [['CN', server_information.server_name]], server_information.site_addresses, 'Middleman Preview Server')
http_opts[:SSLCertificate] = cert
http_opts[:SSLPrivateKey] = key
end
end
http_opts[:Logger] = if is_logging
FilteredWebrickLog.new
else
::WEBrick::Log.new(nil, 0)
end
begin
::WEBrick::HTTPServer.new(http_opts)
rescue Errno::EADDRINUSE
$stderr.puts %(== Port "#{http_opts[:Port]}" is in use. This should not have happened. Please start "middleman server" again.)
end
end
# Copy of https://github.com/nahi/ruby/blob/webrick_trunk/lib/webrick/ssl.rb#L39
# that uses a different serial number each time the cert is generated in order to
# avoid errors in Firefox. Also doesn't print out stuff to $stderr unnecessarily.
def create_self_signed_cert(bits, cn, aliases, comment)
rsa = OpenSSL::PKey::RSA.new(bits)
cert = OpenSSL::X509::Certificate.new
cert.version = 2
cert.serial = Time.now.to_i % (1 << 20)
name = OpenSSL::X509::Name.new(cn)
cert.subject = name
cert.issuer = name
cert.not_before = Time.now
cert.not_after = Time.now + (365 * 24 * 60 * 60)
cert.public_key = rsa.public_key
ef = OpenSSL::X509::ExtensionFactory.new(nil, cert)
ef.issuer_certificate = cert
cert.extensions = [
ef.create_extension('basicConstraints', 'CA:FALSE'),
ef.create_extension('keyUsage', 'keyEncipherment'),
ef.create_extension('subjectKeyIdentifier', 'hash'),
ef.create_extension('extendedKeyUsage', 'serverAuth'),
ef.create_extension('nsComment', comment)
]
aki = ef.create_extension('authorityKeyIdentifier',
'keyid:always,issuer:always')
cert.add_extension(aki)
cert.add_extension ef.create_extension('subjectAltName', aliases.map { |d| "DNS: #{d}" }.join(','))
cert.sign(rsa, OpenSSL::Digest::SHA1.new)
[cert, rsa]
end
# Attach a new Middleman::Application instance
# @param [Middleman::Application] app
# @return [void]
def mount_instance(app)
@app = app
@webrick ||= setup_webrick(@options[:debug] || false)
rack_app = ::Middleman::Rack.new(@app).to_app
require "rackup/handler/webrick"
@webrick.mount '/', ::Rackup::Handler::WEBrick, rack_app
end
# Detach the current Middleman::Application instance
# @return [void]
def unmount_instance
@webrick.unmount '/'
@app.shutdown!
@app = nil
end
end
class FilteredWebrickLog < ::WEBrick::Log
def log(level, data)
super(level, data) unless data =~ %r{Could not determine content-length of response body.}
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/logger.rb | middleman-core/lib/middleman-core/logger.rb | # Use the Ruby/Rails logger
require 'active_support/notifications'
require 'active_support/logger'
require 'thread'
module Middleman
# The Middleman Logger
class Logger < ActiveSupport::Logger
def self.singleton(*args)
if !@_logger || !args || !args.empty?
if args.length == 1 && (args.first.is_a?(::String) || args.first.respond_to?(:write))
args = [0, false, args.first]
end
@_logger = new(*args)
end
@_logger
end
def initialize(log_level=1, is_instrumenting=false, target=$stdout)
super(target)
self.level = log_level
@instrumenting = is_instrumenting
if @instrumenting != false
::ActiveSupport::Notifications.subscribe(/\.middleman$/, self)
end
@mutex = Mutex.new
end
def add(*args)
@mutex.synchronize do
super
end
end
def call(message, *args)
return if @instrumenting.is_a?(String) && @instrumenting != 'instrument' && !message.include?(@instrumenting)
evt = ::ActiveSupport::Notifications::Event.new(message, *args)
return unless evt.duration > 30
info "== Instrument (#{evt.name.sub(/.middleman$/, '')}): #{evt.duration}ms\n#{args.last}"
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/file_renderer.rb | middleman-core/lib/middleman-core/file_renderer.rb | require 'tilt'
require 'active_support/core_ext/string/output_safety'
require 'active_support/core_ext/module/delegation'
require 'middleman-core/contracts'
::Tilt.default_mapping.lazy_map.delete('html')
::Tilt.default_mapping.lazy_map.delete('csv')
module Middleman
class FileRenderer
extend Forwardable
include Contracts
def self.cache
@_cache ||= ::Tilt::Cache.new
end
def_delegator :"self.class", :cache
def initialize(app, path)
@app = app
@path = path.to_s
end
# Render an on-disk file. Used for everything, including layouts.
#
# @param [Hash] locs
# @param [Hash] opts
# @param [Class] context
# @return [String]
Contract Hash, Hash, Any, Maybe[Proc] => String
def render(locs, opts, context, &block)
path = @path.dup
# Detect the remdering engine from the extension
extension = File.extname(path)
engine = extension[1..-1].to_sym
# Store last engine for later (could be inside nested renders)
context.current_engine, engine_was = engine, context.current_engine
# Save current buffer for later
buf_was = context.save_buffer
# Read from disk or cache the contents of the file
body = if opts[:template_body]
opts.delete(:template_body)
else
template_data_for_file
end
# Merge per-extension options from config
extension = File.extname(path)
options = {}.merge!(opts).merge!(options_for_ext(extension))
options[:outvar] ||= '@_out_buf'
options[:context] = context
options.delete(:layout)
# Overwrite with frontmatter options
options = options.deep_merge(options[:renderer_options]) if options[:renderer_options]
template_class = ::Middleman::Util.tilt_class(path)
# Allow hooks to manipulate the template before render
body = @app.callbacks_for(:before_render).reduce(body) do |sum, callback|
callback.call(sum, path, locs, template_class) || sum
end
# Read compiled template from disk or cache
template = ::Tilt.new(path, 1, options) { body.dup }
# Render using Tilt
content = template.render(context, locs, &block)
# Allow hooks to manipulate the result after render
content = @app.callbacks_for(:after_render).reduce(content) do |sum, callback|
callback.call(sum, path, locs, template_class) || sum
end
output = ::ActiveSupport::SafeBuffer.new ''
output.safe_concat content
output
ensure
# Reset stored buffer
context.restore_buffer(buf_was)
context.current_engine = engine_was
end
# Get the template data from a path
# @param [String] path
# @return [String]
Contract String
def template_data_for_file
file = @app.files.find(:source, @path)
if @app.extensions[:front_matter] && (file && !file[:types].include?(:no_frontmatter))
result = @app.extensions[:front_matter].template_data_for_file(@path)
return result unless result.nil?
end
file ? file.read : ::File.read(@path)
end
protected
# Get a hash of configuration options for a given file extension, from
# config.rb
#
# @param [String] ext
# @return [Hash]
Contract String => Hash
def options_for_ext(ext)
# Read options for extension from config/Tilt or cache
cache.fetch(:options_for_ext, ext) do
options = {}
# Find all the engines which handle this extension in tilt. Look for
# config variables of that name and merge it
extension_class = ::Middleman::Util.tilt_class(ext)
::Tilt.default_mapping.extensions_for(extension_class).each do |mapping_ext|
engine_options = @app.config[mapping_ext.to_sym] || {}
options.merge!(engine_options)
end
options
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/callback_manager.rb | middleman-core/lib/middleman-core/callback_manager.rb | require 'hamster'
require 'middleman-core/contracts'
# Immutable Callback Management, complete with Contracts validation.
module Middleman
class CallbackManager
include Contracts
Contract Any
def initialize
@callbacks = ::Hamster::Hash.empty
@subscribers = ::Hamster::Vector.empty
end
Contract RespondTo[:define_singleton_method], ArrayOf[Symbol] => Any
def install_methods!(install_target, names)
manager = self
names.each do |method_name|
install_target.define_singleton_method(method_name) do |*keys, &b|
key_set = keys.unshift(method_name)
manager.add(key_set.length > 1 ? key_set : key_set[0], &b)
end
end
install_target.define_singleton_method(:execute_callbacks) do |*args|
keys = args.shift
manager.execute(keys, args[0], self)
end
install_target.define_singleton_method(:callbacks_for, &method(:callbacks_for))
install_target.define_singleton_method(:subscribe_to_callbacks, &method(:subscribe))
end
Contract Or[Symbol, ArrayOf[Symbol]], Proc => Any
def add(keys, &block)
immutable_keys = keys.is_a?(Symbol) ? keys : ::Hamster::Vector.new(keys)
@callbacks = @callbacks.put(immutable_keys) do |v|
v.nil? ? ::Hamster::Vector.new([block]) : v.push(block)
end
end
Contract Proc => Any
def subscribe(&block)
@subscribers = @subscribers.push(block)
end
Contract Or[Symbol, ArrayOf[Symbol]], Maybe[ArrayOf[Any]], Maybe[RespondTo[:instance_exec]] => Any
def execute(keys, args=[], scope=self)
callbacks = callbacks_for(keys)
callbacks_count = callbacks.length + @subscribers.length
return if callbacks_count < 1
# ::Middleman::Util.instrument "callbacks.execute", keys: keys, length: callbacks_count do
callbacks.each { |b| scope.instance_exec(*args, &b) }
@subscribers.each { |b| scope.instance_exec(keys, args, &b) }
# end
end
Contract Or[Symbol, ArrayOf[Symbol]] => ::Hamster::Vector
def callbacks_for(keys)
immutable_keys = keys.is_a?(Symbol) ? keys : ::Hamster::Vector.new(keys)
@callbacks.get(immutable_keys) || ::Hamster::Vector.empty
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/rack.rb | middleman-core/lib/middleman-core/rack.rb | require 'rack'
require 'rack/files'
require 'rack/lint'
require 'rack/head'
require 'rack/utils'
require 'addressable/uri'
require 'middleman-core/util'
require 'middleman-core/logger'
require 'middleman-core/template_renderer'
# CSSPIE HTC File
::Rack::Mime::MIME_TYPES['.htc'] = 'text/x-component'
# Let's serve all HTML as UTF-8
::Rack::Mime::MIME_TYPES['.html'] = 'text/html; charset=utf-8'
::Rack::Mime::MIME_TYPES['.htm'] = 'text/html; charset=utf-8'
# Sourcemap format
::Rack::Mime::MIME_TYPES['.map'] = 'application/json; charset=utf-8'
# Create a MIME type for PHP files (for detection by extensions)
::Rack::Mime::MIME_TYPES['.php'] = 'text/php'
module Middleman
class Rack
extend Forwardable
def to_app
app = ::Rack::Builder.new
app.use ::Rack::Lint
app.use ::Rack::Head
@middleman.middleware.each do |middleware|
app.use(middleware[:class], *middleware[:options], &middleware[:block])
end
inner_app = self
app.map('/') { run inner_app }
@middleman.mappings.each do |mapping|
app.map(mapping[:path], &mapping[:block])
end
app
end
def_delegator :"::Middleman::Logger", :singleton, :logger
def initialize(middleman)
@middleman = middleman
end
# Rack Interface
#
# @param env Rack environment
def call(env)
# Store environment, request and response for later
req = ::Rack::Request.new(env)
res = ::Rack::Response.new
logger.debug "== Request: #{env['PATH_INFO']}"
# Catch :halt exceptions and use that response if given
catch(:halt) do
process_request(env, req, res)
res.status = 404
res.finish
end
end
# Halt the current request and return a response
#
# @param [String] response Response value
def halt(response)
throw :halt, response
end
# Core response method. We process the request, check with
# the sitemap, and return the correct file, response or status
# message.
#
# @param env
# @param [Rack::Request] req
# @param [Rack::Response] res
def process_request(env, req, res)
start_time = Time.now
request_path = Addressable::URI.unencode(env['PATH_INFO'].dup)
if request_path.respond_to? :force_encoding
request_path.force_encoding('UTF-8')
end
request_path = ::Middleman::Util.full_path(request_path, @middleman)
full_request_path = File.join(env['SCRIPT_NAME'], request_path) # Path including rack mount
# Run before callbacks
@middleman.execute_callbacks(:before)
# Get the resource object for this path
resource = @middleman.sitemap.find_resource_by_destination_path(request_path.gsub(' ', '%20'))
# Return 404 if not in sitemap
return not_found(res, full_request_path) unless resource && !resource.ignored?
# If this path is a binary file, send it immediately
return send_file(resource, env) if resource.binary?
res['content-type'] = resource.content_type || 'text/plain'
begin
# Write out the contents of the page
res.write resource.render({}, rack: { request: req })
# Valid content is a 200 status
res.status = 200
rescue Middleman::TemplateRenderer::TemplateNotFound => e
res.write "Error: #{e.message}"
res.status = 500
end
# End the request
logger.debug "== Finishing Request: #{resource.destination_path} (#{(Time.now - start_time).round(2)}s)"
halt res.finish
end
# Halt request and return 404
def not_found(res, path)
path = ::Rack::Utils.escape_html(path)
res.status = 404
res.write "<html><head></head><body><h1>File Not Found</h1><p>#{path}</p></body></html>"
res.finish
end
# Immediately send static file
def send_file(resource, env)
file = ::Rack::Files.new nil
path = resource.file_descriptor[:full_path].to_s
if !file.respond_to?(:path=)
request = ::Rack::Request.new(env)
response = file.serving(request, path)
else
file.path = path
response = file.serving(env)
end
status = response[0]
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).cover?(status) && ![204, 205, 304].include?(status)
response[1]['content-type'] = resource.content_type || 'application/octet-stream'
end
halt response
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/configuration.rb | middleman-core/lib/middleman-core/configuration.rb | module Middleman
module Configuration
# A class that manages a collection of documented settings.
# Can be used by extensions as well as the main Middleman
# application. Extensions should probably finalize their instance
# after defining all the settings they want to expose.
class ConfigurationManager
def initialize
# A hash from setting key to ConfigSetting instance.
@settings = {}
@finalized = false
end
# Get all settings, sorted by key, as ConfigSetting objects.
# @return [Array<ConfigSetting>]
def all_settings
@settings.values.sort_by(&:key)
end
# Get a full ConfigSetting object for the setting with the give key.
# @return [ConfigSetting]
def setting(key)
@settings[key]
end
# Get the value of a setting by key. Returns nil if there is no such setting.
# @return [Object]
def [](key)
setting_obj = setting(key)
setting_obj ? setting_obj.value : nil
end
# Set the value of a setting by key. Creates the setting if it doesn't exist.
# @param [Symbol] key
# @param [Object] val
def []=(key, val)
setting_obj = setting(key) || define_setting(key)
setting_obj.value = val
end
# Allow configuration settings to be read and written via methods
def method_missing(method, *args)
if defines_setting?(method) && args.empty?
self[method]
elsif method.to_s =~ /^(\w+)=$/ && args.size == 1
self[$1.to_sym] = args[0]
else
super
end
end
# Needed so that method_missing makes sense
def respond_to?(method, include_private=false)
super || defines_setting?(method) || (method =~ /^(\w+)=$/ && defines_setting?($1))
end
# Does this configuration manager know about the setting identified by key?
# @param [Symbol] key
# @return [Boolean]
def defines_setting?(key)
@settings.key?(key)
end
# Define a new setting, with optional default and user-friendly description.
# Once the configuration manager is finalized, no new settings may be defined.
#
# @example
# config.define_setting :compress, false, 'Whether to compress the output'
# @param [Symbol] key The name of the option
# @param [Object] default The default value for the option
# @param [String] description A human-readable description of what the option does
# @param [Hash] options Additional options.
# @return [ConfigSetting]
def define_setting(key, default=nil, description=nil, options={})
raise "Setting #{key} doesn't exist" if @finalized
raise "Setting #{key} already defined" if @settings.key?(key)
raise 'Setting key must be a Symbol' unless key.is_a? Symbol
@settings[key] = ConfigSetting.new(key, default, description, options)
end
# Switch the configuration manager is finalized, it switches to read-only
# mode and no new settings may be defined.
def finalize!
@finalized = true
self
end
# Deep duplicate of the configuration manager
def dup
ConfigurationManager.new.tap { |c| c.load_settings(all_settings) }
end
# Load in a list of settings
def load_settings(other_settings)
other_settings.each do |setting|
new_setting = define_setting(setting.key, setting.default, setting.description, setting.options)
new_setting.value = setting.value if setting.value_set?
end
end
def to_h
hash = {}
@settings.each do |key, setting|
hash[key] = setting.value
end
hash
end
def to_s
to_h.inspect
end
end
# An individual configuration setting, with an optional default and description.
# Also models whether or not a value has been set.
class ConfigSetting
# The name of this setting
attr_accessor :key
# The default value for this setting
attr_accessor :default
# A human-friendly description of the setting
attr_accessor :description
# Additional config.
attr_accessor :options
def initialize(key, default, description, options={})
@value_set = false
self.key = key
self.default = default
self.description = description
self.options = options
end
# The user-supplied value for this setting, overriding the default
def value=(value)
@value = value
@value_set = true
end
# The effective value of the setting, which may be the default
# if the user has not set a value themselves. Note that even if the
# user sets the value to nil it will override the default.
def value
value_set? ? @value : default
end
# Whether or not there has been a value set beyond the default
def value_set?
@value_set == true
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/template_renderer.rb | middleman-core/lib/middleman-core/template_renderer.rb | require 'tilt'
require 'active_support/core_ext/string/output_safety'
require 'middleman-core/template_context'
require 'middleman-core/file_renderer'
require 'middleman-core/contracts'
module Middleman
class TemplateRenderer
extend Forwardable
include Contracts
class Cache
def initialize
@cache = {}
end
def fetch(*key)
@cache[key] = yield unless @cache.key?(key)
@cache[key]
end
def clear
@cache = {}
end
end
def self.cache
@_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 = ::Middleman::Util.tilt_class(options[:preferred_engine])
# Get a list of extensions for a preferred engine
preferred_engines += ::Tilt.default_mapping.extensions_for(extension_class)
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? || ::Middleman::Util.tilt_class(file[:full_path].to_s))
break if found_template
end
# If we found one, return it
found_template
end
# Custom error class for handling
class TemplateNotFound < RuntimeError; end
def initialize(app, path)
@app = app
@path = path
end
# Render a template, with layout, given a path
#
# @param [Hash] locs
# @param [Hash] opts
# @return [String]
Contract Hash, Hash => String
def render(locs={}, opts={}, &block)
path = @path.dup
locals = locs.dup.freeze
options = opts.dup
extension = File.extname(path)
engine = extension[1..-1].to_sym
if defined?(::I18n)
old_locale = ::I18n.locale
::I18n.locale = options.delete(:locale) if options[:locale]
# Backwards compat
::I18n.locale = options.delete(:lang) if options[:lang]
end
# Sandboxed class for template eval
context = @app.template_context_class.new(@app, locals, options)
# Add extension helpers to context.
@app.extensions.add_exposed_to_context(context)
locals.each do |k, _|
next unless context.respond_to?(k) && ![:current_path, :paginate, :page_articles, :blog_controller, :lang, :locale, :data].include?(k.to_sym)
msg = "Template local `#{k}` tried to overwrite an existing context value. Please rename the key when passing to `locals`"
if @app.build?
throw msg
else
@app.logger.error(msg)
end
end
content = ::Middleman::Util.instrument 'builder.output.resource.render-template', path: File.basename(path) do
_render_with_all_renderers(path, locals, context, options, &block)
end
# If we need a layout and have a layout, use it
layout_file = fetch_layout(engine, options)
if layout_file
content = if layout_file = fetch_layout(engine, options)
layout_renderer = ::Middleman::FileRenderer.new(@app, layout_file[:relative_path].to_s)
::Middleman::Util.instrument 'builder.output.resource.render-layout', path: File.basename(layout_file[:relative_path].to_s) do
layout_renderer.render(locals, options, context) { content }
end
else
content
end
end
# Return result
content
ensure
# Pop all the saved variables from earlier as we may be returning to a
# previous render (layouts, partials, nested layouts).
::I18n.locale = old_locale if defined?(::I18n)
end
protected
def _render_with_all_renderers(path, locs, context, opts, &block)
# Keep rendering template until we've used up all extensions. This
# handles cases like `style.css.sass.erb`
content = nil
while ::Middleman::Util.tilt_class(path)
begin
opts[:template_body] = content if content
content_renderer = ::Middleman::FileRenderer.new(@app, path)
content = content_renderer.render(locs, opts, context, &block)
path = File.basename(path, File.extname(path))
rescue LocalJumpError
raise "Tried to render a layout (calls yield) at #{path} like it was a template. Non-default layouts need to be in #{@app.config[:source]}/#{@app.config[:layouts_dir]}."
end
end
content
end
# Find a layout for a given engine
#
# @param [Symbol] engine
# @param [Hash] opts
# @return [String, Boolean]
Contract Symbol, Hash => Maybe[IsA['Middleman::SourceFile']]
def fetch_layout(engine, opts)
# The layout name comes from either the system default or the options
local_layout = opts.key?(:layout) ? opts[:layout] : @app.config[:layout]
return unless local_layout
# Look for engine-specific options
engine_options = @app.config.respond_to?(engine) ? @app.config.send(engine) : {}
# The engine for the layout can be set in options, engine_options or passed
# into this method
layout_engine = if opts.key?(:layout_engine)
opts[:layout_engine]
elsif engine_options.key?(:layout_engine)
engine_options[:layout_engine]
else
engine
end
# Automatic mode
if local_layout == :_auto_layout
# Look for :layout of any extension
# If found, use it. If not, continue
locate_layout(:layout, layout_engine)
elsif layout_file = locate_layout(local_layout, layout_engine)
# Look for specific layout
# If found, use it. If not, error.
layout_file
else
raise ::Middleman::TemplateRenderer::TemplateNotFound, "Could not locate layout: #{local_layout}"
end
end
# Find a layout on-disk, optionally using a specific engine
# @param [String] name
# @param [Symbol] preferred_engine
# @return [String]
Contract Or[String, Symbol], Symbol => Maybe[IsA['Middleman::SourceFile']]
def locate_layout(name, preferred_engine=nil)
self.class.locate_layout(@app, name, preferred_engine)
end
# Find a template on disk given a output path
# @param [String] request_path
# @param [Hash] options
# @return [Array<String, Symbol>, Boolean]
Contract String, Hash => ArrayOf[Or[String, Symbol]]
def resolve_template(request_path, options={})
self.class.resolve_template(@app, request_path, options)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/dns_resolver.rb | middleman-core/lib/middleman-core/dns_resolver.rb | require 'resolv'
require 'middleman-core/dns_resolver/network_resolver'
require 'middleman-core/dns_resolver/hosts_resolver'
module Middleman
# This resolves IP address to names and vice versa
class DnsResolver
private
attr_reader :resolvers
public
# Create resolver
#
# First the local resolver is used. If environment variable HOSTSRC is
# given this file is used for local name lookup.
#
# @param [#getnames, #getaddresses] network_resolver
# The resolver which uses a network name server to resolve ip addresses
# and names.
#
# @param [#getnames, #getaddresses] local_resolver
# The resolver uses /etc/hosts on POSIX-systems and
# C:\Windows\System32\drivers\etc\hosts on Windows-operating systems to
# resolve ip addresses and names.
#
# First the local resolver is queried. If this raises an error or returns
# nil or [] the network resolver is queried.
def initialize(opts={})
@resolvers = []
@resolvers << opts.fetch(:hosts_resolver, HostsResolver.new)
require 'middleman-core/dns_resolver/local_link_resolver'
@resolvers << opts.fetch(:local_link_resolver, LocalLinkResolver.new)
@resolvers << opts.fetch(:network_resolver, NetworkResolver.new)
end
# Get names for given ip
#
# @param [String] ip
# The ip which should be resolved.
def names_for(ip)
resolvers.each do |r|
names = r.getnames(ip)
return names unless names.nil? || names.empty?
end
[]
end
# Get ips for given name
#
# First the local resolver is used. On POSIX-systems /etc/hosts is used. On
# Windows C:\Windows\System32\drivers\etc\hosts is used.
#
# @param [String] name
# The name which should be resolved.
def ips_for(name)
resolvers.each do |r|
ips = r.getaddresses(name)
return ips unless ips.nil? || ips.empty?
end
[]
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/contracts.rb | middleman-core/lib/middleman-core/contracts.rb | if ENV['CONTRACTS'] != 'false'
require 'contracts'
require 'hamster'
module Contracts
class IsA
def self.[](val)
@lookup ||= {}
@lookup[val] ||= new(val)
end
def initialize(val)
@val = val
end
def valid?(val)
val.is_a? @val.constantize
end
end
VectorOf = Contracts::CollectionOf::Factory.new(::Hamster::Vector)
ResourceList = Contracts::ArrayOf[IsA['Middleman::Sitemap::Resource']]
end
else
module Contracts
def self.included(base)
base.extend self
end
def Contract(*); end
class Callable
def self.[](*)
end
end
class Bool
end
class Num
end
class Pos
end
class Neg
end
class Any
end
class None
end
class Or < Callable
end
class Xor < Callable
end
class And < Callable
end
class Not < Callable
end
class RespondTo < Callable
end
class Send < Callable
end
class Exactly < Callable
end
class ArrayOf < Callable
end
class ResourceList < Callable
end
class Args < Callable
end
class HashOf < Callable
end
class Bool
end
class Maybe < Callable
end
class IsA < Callable
end
class SetOf < Callable
end
class Frozen < Callable
end
class VectorOf < Callable
end
end
end
module Contracts
PATH_MATCHER = Or[String, RespondTo[:match], RespondTo[:call], RespondTo[:to_s]]
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/step_definitions.rb | middleman-core/lib/middleman-core/step_definitions.rb | require 'aruba/cucumber'
require 'middleman-core/step_definitions/middleman_steps'
require 'middleman-core/step_definitions/builder_steps'
require 'middleman-core/step_definitions/server_steps'
require 'middleman-core/step_definitions/commandline_steps'
# Monkeypatch for windows support
module ArubaMonkeypatch
def detect_ruby(cmd)
if cmd.start_with?('middleman ') && Gem.win_platform?
"#{current_ruby} #{Dir.pwd}/../middleman-cli/bin/#{cmd}"
else
cmd.sub(/^ruby(?= )/, current_ruby)
end
end
end
World(ArubaMonkeypatch)
# The Capybara monkey-patch that switches between RSpec::Matchers#all and Capybara::DSL#all
World(Capybara::RSpecMatcherProxies)
Before do
@aruba_timeout_seconds = RUBY_PLATFORM == 'java' ? 120 : 60
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/builder.rb | middleman-core/lib/middleman-core/builder.rb | require 'addressable/uri'
require 'pathname'
require 'fileutils'
require 'tempfile'
require 'parallel'
require 'middleman-core/rack'
require 'middleman-core/callback_manager'
require 'middleman-core/contracts'
module Middleman
class Builder
extend Forwardable
include Contracts
# Make app & events available to `after_build` callbacks.
attr_reader :app, :events
# Reference to the Thor class.
attr_accessor :thor
# Logger comes from App.
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).freeze
# Create a new Builder instance.
# @param [Middleman::Application] app The app to build.
# @param [Hash] opts The builder options
def initialize(app, opts={})
@app = app
@source_dir = Pathname(File.join(@app.root, @app.config[:source]))
@build_dir = Pathname(@app.config[:build_dir])
if @build_dir.expand_path.relative_path_from(@source_dir).to_s =~ /\A[.\/]+\Z/
raise ":build_dir (#{@build_dir}) cannot be a parent of :source_dir (#{@source_dir})"
end
@glob = opts.fetch(:glob)
@cleaning = opts.fetch(:clean)
@parallel = opts.fetch(:parallel, true)
rack_app = ::Middleman::Rack.new(@app).to_app
@rack = ::Rack::MockRequest.new(rack_app)
@callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [:on_build_event])
end
# Run the build phase.
# @return [Boolean] Whether the build was successful.
Contract Bool
def run!
@has_error = false
@events = {}
::Middleman::Util.instrument 'builder.before' do
@app.execute_callbacks(:before_build, [self])
end
::Middleman::Util.instrument 'builder.queue' do
queue_current_paths if @cleaning
end
::Middleman::Util.instrument 'builder.prerender' do
prerender_css
end
::Middleman::Profiling.start
::Middleman::Util.instrument 'builder.output' do
output_files
end
::Middleman::Profiling.report('build')
unless @has_error
::Middleman::Util.instrument 'builder.clean' do
clean! if @cleaning
end
::Middleman::Util.instrument 'builder.after' do
@app.execute_callbacks(:after_build, [self])
end
end
!@has_error
end
# Pre-request CSS to give Sass a chance to build sprites
# @return [Array<Resource>] List of css resources that were output.
Contract ResourceList
def prerender_css
logger.debug '== Prerendering CSS'
css_files = ::Middleman::Util.instrument 'builder.prerender.output' do
resources = @app.sitemap.resources.select { |resource| resource.ext == '.css' }
output_resources(resources)
end
::Middleman::Util.instrument 'builder.prerender.check-files' do
# Double-check for Sass sprites
unless @app.files.find_new_files!.empty?
logger.debug '== Checking for Sass sprites'
@app.sitemap.ensure_resource_list_updated!
end
end
css_files
end
# Find all the files we need to output and do so.
# @return [Array<Resource>] List of resources that were output.
Contract ResourceList
def output_files
logger.debug '== Building files'
resources = @app.sitemap.resources
.reject { |resource| resource.ext == '.css' }
.sort_by { |resource| SORT_ORDER.index(resource.ext) || 100 }
if @glob
resources = resources.select do |resource|
if defined?(::File::FNM_EXTGLOB)
File.fnmatch(@glob, resource.destination_path, ::File::FNM_EXTGLOB)
else
File.fnmatch(@glob, resource.destination_path)
end
end
end
output_resources(resources)
end
Contract ResourceList => ResourceList
def output_resources(resources)
results = if @parallel
::Parallel.map(resources, &method(:output_resource))
else
resources.map(&method(:output_resource))
end
@has_error = true if results.any? { |r| r == false }
if @cleaning && !@has_error
results.each do |p|
next unless p.exist?
# handle UTF-8-MAC filename on MacOS
cleaned_name = if RUBY_PLATFORM =~ /darwin/
p.to_s.encode('UTF-8', 'UTF-8-MAC')
else
p
end
@to_clean.delete(Pathname(cleaned_name))
end
end
resources
end
# Figure out the correct event mode.
# @param [Pathname] output_file The output file path.
# @param [String] source The source file path.
# @return [Symbol]
Contract Pathname, String => Symbol
def which_mode(output_file, source)
if !output_file.exist?
:created
else
FileUtils.compare_file(source.to_s, output_file.to_s) ? :identical : :updated
end
end
# Create a tempfile for a given output with contents.
# @param [Pathname] output_file The output path.
# @param [String] contents The file contents.
# @return [Tempfile]
Contract Pathname, String => Tempfile
def write_tempfile(output_file, contents)
file = Tempfile.new([
File.basename(output_file),
File.extname(output_file)
])
file.binmode
file.write(contents)
file.close
File.chmod(0o644, file)
file
end
# Actually export the file.
# @param [Pathname] output_file The path to output to.
# @param [String|Pathname] source The source path or contents.
# @return [void]
Contract Pathname, Or[String, Pathname] => Any
def export_file!(output_file, source)
# ::Middleman::Util.instrument "write_file", output_file: output_file do
source = write_tempfile(output_file, source.to_s) if source.is_a? String
method, source_path = if source.is_a? Tempfile
[::FileUtils.method(:mv), source.path]
else
[::FileUtils.method(:cp), source.to_s]
end
mode = which_mode(output_file, source_path)
if mode == :created || mode == :updated
::FileUtils.mkdir_p(output_file.dirname)
method.call(source_path, output_file.to_s)
end
source.unlink if source.is_a? Tempfile
trigger(mode, output_file)
# end
end
# Try to output a resource and capture errors.
# @param [Middleman::Sitemap::Resource] resource The resource.
# @return [void]
Contract IsA['Middleman::Sitemap::Resource'] => Or[Pathname, Bool]
def output_resource(resource)
::Middleman::Util.instrument 'builder.output.resource', path: File.basename(resource.destination_path) do
output_file = @build_dir + resource.destination_path.gsub('%20', ' ')
begin
if resource.binary?
export_file!(output_file, resource.file_descriptor[:full_path])
else
response = @rack.get(Addressable::URI.encode(resource.request_path))
# If we get a response, save it to a tempfile.
if response.status == 200
export_file!(output_file, binary_encode(response.body))
else
trigger(:error, output_file, response.body)
return false
end
end
rescue => e
trigger(:error, output_file, "#{e}\n#{e.backtrace.join("\n")}")
return false
end
output_file
end
end
# Get a list of all the paths in the destination folder and save them
# for comparison against the files we build in this cycle
# @return [void]
Contract Any
def queue_current_paths
@to_clean = []
return unless File.exist?(@app.config[:build_dir])
paths = ::Middleman::Util.all_files_under(@app.config[:build_dir]).map do |path|
Pathname(path)
end
@to_clean = paths.select do |path|
path.realpath.relative_path_from(@build_dir.realpath).to_s !~ /\/\./ || path.to_s =~ /\.(htaccess|htpasswd)/
end
# handle UTF-8-MAC filename on MacOS
@to_clean = @to_clean.map do |path|
if RUBY_PLATFORM =~ /darwin/
Pathname(path.to_s.encode('UTF-8', 'UTF-8-MAC'))
else
Pathname(path)
end
end
end
# Remove files which were not built in this cycle
Contract ArrayOf[Pathname]
def clean!
to_remove = @to_clean.reject do |f|
app.config[:skip_build_clean].call(f.to_s)
end
to_remove.each do |f|
FileUtils.rm(f)
trigger(:deleted, f)
end
end
Contract String => String
def binary_encode(string)
string.force_encoding('ascii-8bit') if string.respond_to?(:force_encoding)
string
end
Contract Symbol, Or[String, Pathname], Maybe[String] => Any
def trigger(event_type, target, extra=nil)
@events[event_type] ||= []
@events[event_type] << target
execute_callbacks(:on_build_event, [event_type, target, extra])
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extension.rb | middleman-core/lib/middleman-core/extension.rb | require 'forwardable'
require 'memoist'
require 'active_support/core_ext/class/attribute'
require 'middleman-core/configuration'
require 'middleman-core/contracts'
module Middleman
# Middleman's Extension API provides the ability to add functionality to Middleman
# and to customize existing features. Internally, most features in Middleman are
# implemented as extensions. A good way to figure out how to write your own extension
# is to look at the source of the built-in extensions or popular extension gems like
# `middleman-blog` or `middleman-syntax`.
#
# The most basic extension looks like:
#
# class MyFeature < Middleman::Extension
# def initialize(app, options_hash={}, &block)
# super
# end
# end
# ::Middleman::Extensions.register(:my_feature, MyFeature)
#
# A more complicated example might look like:
#
# class MyFeature < Middleman::Extension
# option :my_option, 'cool', 'A very cool option'
#
# def initialize(app, options_hash={}, &block)
# super
# puts "My option is #{options.my_option}"
# end
#
# def after_configuration
# puts "The project has been configured"
# end
#
# def manipulate_resource_list(resources)
# resources.each do |resource|
# # Make all .jpg's get built or served with a .jpeg extension.
# if resource.ext == '.jpg'
# resource.destination_path = resource.destination_path.sub('.jpg', '.jpeg')
# end
# end
# end
# end
#
# ::Middleman::Extensions.register :my_feature do
# MyFeature
# end
#
# Extensions can add helpers (via {Extension.helpers}), add to the sitemap or change it (via {#manipulate_resource_list}), or run
# arbitrary code at different parts of the Middleman application's lifecycle. They can have options (defined via {Extension.option} and accessed via {#options}).
#
# Common lifecycle events can be handled by extensions simply by implementing an appropriately-named method:
#
# * {#after_configuration}
# * {#after_build}
# * {#before_build}
#
# There are also some less common hooks that can be listened to from within an extension's `initialize` method:
#
# * `app.before_render {|body, path, locs, template_class| ... }` - Manipulate template sources before they are rendered.
# * `app.after_render {|content, path, locs, template_class| ... }` - Manipulate output text after a template has been rendered. It is also common to install a Rack middleware to do this instead.
# * `app.ready { ... }` - Run code once Middleman is ready to serve or build files (after `after_configuration`).
#
# @see http://middlemanapp.com/advanced/custom/ Middleman Custom Extensions Documentation
class Extension
extend Forwardable
extend Memoist
include Contracts
def_delegator :@app, :logger
# @!attribute supports_multiple_instances
# @!scope class
# @return [Boolean] whether or not an extension can be activated multiple times, generating multiple instances of the extension.
# By default extensions can only be activated once in a project. This is an advanced option.
class_attribute :supports_multiple_instances, instance_reader: false, instance_writer: false
# @!attribute defined_helpers
# @!scope class
# @api private
# @return [Array<Module>] a list of all the helper modules this extension provides. Set these using {#helpers}.
class_attribute :defined_helpers, instance_reader: false, instance_writer: false
# @!attribute exposed_to_application
# @!scope class
# @api private
# @return [Hash<Symbol, Symbol>] a list of all the methods modules this extension exposes to app. Set these using {#expose_to_application}.
class_attribute :exposed_to_application, instance_reader: false, instance_writer: false
# @!attribute exposed_to_config
# @!scope class
# @api private
# @return [Hash<Symbol, Symbol>] a list of all the methods modules this extension exposes to config. Set these using {#expose_to_config}.
class_attribute :exposed_to_config, instance_reader: false, instance_writer: false
# @!attribute exposed_to_template
# @!scope class
# @api private
# @return [Hash<Symbol, Symbol>] a list of all the methods modules this extension exposes to templates. Set these using {#expose_to_template}.
class_attribute :exposed_to_template, instance_reader: false, instance_writer: false
# @!attribute exposed_to_template
# @!scope class
# @api private
# @return [Array<Any>] a list of method generators.
class_attribute :resources_generators, instance_reader: false, instance_writer: false
# @!attribute ext_name
# @!scope class
# @return [Symbol] the name this extension is registered under. This is the symbol used to activate the extension.
class_attribute :ext_name, instance_reader: false, instance_writer: false
# @!attribute resource_list_manipulator_priority
# @!scope class
# @return [Numeric] the priority for this extension's `manipulate_resource_list` method, if it has one.
# @see Middleman::Sitemap::Store#register_resource_list_manipulator
class_attribute :resource_list_manipulator_priority, instance_reader: false, instance_writer: false
class << self
# @api private
# @return [Middleman::Configuration::ConfigurationManager] The defined options for this extension.
def config
@_config ||= ::Middleman::Configuration::ConfigurationManager.new
end
# Add an option to this extension.
# @see Middleman::Configuration::ConfigurationManager#define_setting
# @example
# option :compress, false, 'Whether to compress the output'
# @param [Symbol] key The name of the option
# @param [Object] default The default value for the option
# @param [String] description A human-readable description of what the option does
def option(key, default=nil, description=nil, options={})
config.define_setting(key, default, description, options)
end
# @api private
# @return [Middleman::Configuration::ConfigurationManager] The defined global options for this extension.
def global_config
@_global_config ||= ::Middleman::Configuration::ConfigurationManager.new
end
# Add an global option to this extension.
# @see Middleman::Configuration::ConfigurationManager#define_setting
# @example
# option :compress, false, 'Whether to compress the output'
# @param [Symbol] key The name of the option
# @param [Object] default The default value for the option
# @param [String] description A human-readable description of what the option does
def define_setting(key, default=nil, description=nil, options={})
global_config.define_setting(key, default, description, options)
end
# Short-hand for simple Sitemap manipulation
# @example A generator which returns an array of resources
# resources :make_resources
# @example A generator which maps a path to a method
# resources make_resource: :make_it
# @example A generator which maps a path to a string
# resources make_resource: 'Hello'
# @param [Array] generators The generator definitions
def resources(*generators)
self.resources_generators ||= []
self.resources_generators += generators
end
# Declare helpers to be added the global Middleman application.
# This accepts either a list of modules to add on behalf
# of this extension, or a block whose contents will all
# be used as helpers in a new module.
# @example With a block:
# helpers do
# def my_helper
# "I helped!"
# end
# end
# @example With modules:
# helpers FancyHelpers, PlainHelpers
# @param [Array<Module>] modules An optional list of modules to add as helpers
# @param [Proc] block A block which will be evaluated to create a new helper module
# @return [void]
def helpers(*modules, &block)
self.defined_helpers ||= []
if block_given?
mod = Module.new
mod.module_eval(&block)
modules = [mod]
end
self.defined_helpers += modules
end
# Takes a method within this extension and exposes it globally
# on the main `app` instance. Used for very low-level extensions
# which many other extensions depend upon. Such as Data and
# File watching.
# @example with Hash:
# expose_to_application global_name: :local_name
# @example with Array:
# expose_to_application :method1, :method2
# @param [Array<Sumbol>, Hash<Symbol, Symbol>] symbols An optional list of symbols representing instance methods to exposed.
# @return [void]
def expose_to_application(*symbols)
self.exposed_to_application ||= {}
if symbols.first && symbols.first.is_a?(Hash)
self.exposed_to_application.merge!(symbols.first)
elsif symbols.is_a? Array
symbols.each do |sym|
self.exposed_to_application[sym] = sym
end
end
end
# Takes a method within this extension and exposes it inside the scope
# of the config.rb sandbox.
# @example with Hash:
# expose_to_config global_name: :local_name
# @example with Array:
# expose_to_config :method1, :method2
# @param [Array<Sumbol>, Hash<Symbol, Symbol>] symbols An optional list of symbols representing instance methods to exposed.
# @return [void]
def expose_to_config(*symbols)
self.exposed_to_config ||= {}
if symbols.first && symbols.first.is_a?(Hash)
self.exposed_to_config.merge!(symbols.first)
elsif symbols.is_a? Array
symbols.each do |sym|
self.exposed_to_config[sym] = sym
end
end
end
# Takes a method within this extension and exposes it inside the scope
# of the templating engine. Like `helpers`, but scoped.
# @example with Hash:
# expose_to_template global_name: :local_name
# @example with Array:
# expose_to_template :method1, :method2
# @param [Array<Sumbol>, Hash<Symbol, Symbol>] symbols An optional list of symbols representing instance methods to exposed.
# @return [void]
def expose_to_template(*symbols)
self.exposed_to_template ||= {}
if symbols.first && symbols.first.is_a?(Hash)
self.exposed_to_template.merge!(symbols.first)
elsif symbols.is_a? Array
symbols.each do |sym|
self.exposed_to_template[sym] = sym
end
end
end
# Reset all {Extension.after_extension_activated} callbacks.
# @api private
# @return [void]
def clear_after_extension_callbacks
@_extension_activation_callbacks = {}
end
# Register to run a block after a named extension is activated.
# @param [Symbol] name The name the extension was registered under
# @param [Proc] block A callback to run when the named extension is activated
# @return [void]
def after_extension_activated(name, &block)
@_extension_activation_callbacks ||= {}
@_extension_activation_callbacks[name] ||= []
@_extension_activation_callbacks[name] << block if block_given?
end
# Notify that a particular extension has been activated and run all
# registered {Extension.after_extension_activated} callbacks.
# @api private
# @param [Middleman::Extension] instance Activated extension instance
# @return [void]
def activated_extension(instance)
name = instance.class.ext_name
return unless @_extension_activation_callbacks && @_extension_activation_callbacks.key?(name)
@_extension_activation_callbacks[name].each do |block|
block.arity == 1 ? block.call(instance) : block.call
end
end
end
# @return [Middleman::Configuration::ConfigurationManager] options for this extension instance.
attr_reader :options
# @return [Middleman::Application] the Middleman application instance.
attr_reader :app
# @!method after_extension_activated(name, &block)
# Register to run a block after a named extension is activated.
# @param [Symbol] name The name the extension was registered under
# @param [Proc] block A callback to run when the named extension is activated
# @return [void]
def_delegator :"::Middleman::Extension", :after_extension_activated
# Extensions are instantiated when they are activated.
# @param [Middleman::Application] app The Middleman::Application instance
# @param [Hash] options_hash The raw options hash. Subclasses should not manipulate this directly - it will be turned into {#options}.
# @yield An optional block that can be used to customize options before the extension is activated.
# @yieldparam [Middleman::Configuration::ConfigurationManager] options Extension options
def initialize(app, options_hash={}, &block)
@_helpers = []
@app = app
expose_methods
setup_options(options_hash, &block)
# Bind app hooks to local methods
bind_before_configuration
bind_after_configuration
bind_before_build
bind_after_build
bind_ready
end
# @!method before_configuration
# Respond to the `before_configuration` event.
# If a `before_configuration` method is implemented, that method will be run before `config.rb` is run.
# @note Because most extensions are activated from within `config.rb`, they *will not run* any `before_configuration` hook.
# @!method after_configuration
# Respond to the `after_configuration` event.
# If an `after_configuration` method is implemented, that method will be run before `config.rb` is run.
# @!method before_build
# Respond to the `before_build` event.
# If an `before_build` method is implemented, that method will be run before the builder runs.
# @!method after_build
# Respond to the `after_build` event.
# If an `after_build` method is implemented, that method will be run after the builder runs.
# @!method ready
# Respond to the `ready` event.
# If an `ready` method is implemented, that method will be run after the app has finished booting up.
# @!method manipulate_resource_list(resources)
# Manipulate the resource list by transforming or adding {Sitemap::Resource}s.
# Sitemap manipulation is a powerful way of interacting with a project, since it can modify each {Sitemap::Resource} or generate new {Sitemap::Resources}. This method is used in a pipeline where each sitemap manipulator is run in turn, with each one being fed the output of the previous manipulator. See the source of built-in Middleman extensions like {Middleman::Extensions::DirectoryIndexes} and {Middleman::Extensions::AssetHash} for examples of how to use this.
# @note This method *must* return the full set of resources, because its return value will be used as the new sitemap.
# @see http://middlemanapp.com/advanced/sitemap/ Sitemap Documentation
# @see Sitemap::Store
# @see Sitemap::Resource
# @param [Array<Sitemap::Resource>] resources A list of all the resources known to the sitemap.
# @return [Array<Sitemap::Resource>] The transformed list of resources.
def add_exposed_to_context(context)
(self.class.exposed_to_template || {}).each do |k, v|
context.define_singleton_method(k, &method(v))
end
end
private
def expose_methods
(self.class.exposed_to_application || {}).each do |k, v|
app.define_singleton_method(k, &method(v))
end
(self.class.exposed_to_config || {}).each do |k, v|
app.config_context.define_singleton_method(k, &method(v))
end
(self.class.defined_helpers || []).each do |m|
app.template_context_class.send(:include, m)
end
end
# @yield An optional block that can be used to customize options before the extension is activated.
# @yieldparam Middleman::Configuration::ConfigurationManager] options Extension options
def setup_options(options_hash)
@options = self.class.config.dup
@options.finalize!
options_hash.each do |k, v|
@options[k] = v
end
yield @options, self if block_given?
@options.all_settings.each do |o|
next unless o.options[:required] && !o.value_set?
logger.error "The `:#{o.key}` option of the `#{self.class.ext_name}` extension is required."
exit(1)
end
end
def bind_before_configuration
@app.before_configuration(&method(:before_configuration)) if respond_to?(:before_configuration)
end
def bind_after_configuration
ext = self
@app.after_configuration do
ext.after_configuration if ext.respond_to?(:after_configuration)
if ext.respond_to?(:manipulate_resource_list)
ext.app.sitemap.register_resource_list_manipulators(ext.class.ext_name, ext, ext.class.resource_list_manipulator_priority)
end
if ext.class.resources_generators && !ext.class.resources_generators.empty?
ext.app.sitemap.register_resource_list_manipulators(
:"#{ext.class.ext_name}_generator",
ext,
ext.class.resource_list_manipulator_priority,
:generate_resources
)
end
end
end
def generate_resources(resources)
generator_defs = self.class.resources_generators.reduce({}) do |sum, g|
resource_definitions = if g.is_a? Hash
g
elsif g.is_a? Symbol
definition = method(g)
if definition.arity == 0
send(g)
else
send(g, resources)
end
else
{}
end
sum.merge!(resource_definitions)
end
resources + generator_defs.map do |path, g|
if g.is_a? Symbol
definition = method(g)
g = if definition.arity == 0
send(g)
else
send(g, resources)
end
end
::Middleman::Sitemap::StringResource.new(
app.sitemap,
path,
g
)
end
end
def bind_before_build
ext = self
return unless ext.respond_to?(:before_build)
@app.before_build do |builder|
if ext.method(:before_build).arity == 1
ext.before_build(builder)
else
ext.before_build
end
end
end
def bind_after_build
ext = self
return unless ext.respond_to?(:after_build)
@app.after_build do |builder|
if ext.method(:after_build).arity == 1
ext.after_build(builder)
elsif ext.method(:after_build).arity == 2
ext.after_build(builder, builder.thor)
else
ext.after_build
end
end
end
def bind_ready
@app.ready(&method(:ready)) if respond_to?(:ready)
end
end
class ConfigExtension < Extension
def initialize(app, config={}, &block)
@descriptors = {}
@ready = false
self.class.exposed_to_config.each do |k, v|
@descriptors[k] = []
define_singleton_method(:"__original_#{v}", &method(v))
define_singleton_method(v) do |*args, &b|
proxy_method_call(k, v, args, &b)
end
end
super
end
def after_configuration
context = self
self.class.exposed_to_config.each do |k, v|
::Middleman::CoreExtensions::Collections::StepContext.add_to_context(k) do |*args, &b|
r = context.method(:"__original_#{v}").call(*args, &b)
descriptors << r if r.respond_to?(:execute_descriptor)
end
end
end
def ready
@ready = true
# @descriptors.each do |k, v|
# @descriptors[k] = []
# end
end
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
@descriptors.values.flatten.reduce(resources) do |sum, c|
c.execute_descriptor(app, sum)
end
end
Contract Symbol, Symbol, ArrayOf[Any], Maybe[Proc] => Any
def proxy_method_call(k, v, args, &b)
if @ready
ctx = ::Middleman::CoreExtensions::Collections::StepContext.current
r = method(:"__original_#{v}").call(*args, &b)
if r.respond_to?(:execute_descriptor)
if ctx
ctx.descriptors << r
else
@descriptors[k] << r
@app.sitemap.rebuild_resource_list!(:"first_run_change_#{v}")
end
end
else
@descriptors[k] << method(:"__original_#{v}").call(*args, &b)
@app.sitemap.rebuild_resource_list!(:"first_run_change_#{v}")
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/config_context.rb | middleman-core/lib/middleman-core/config_context.rb | require 'rack/mime'
require 'middleman-core/callback_manager'
module Middleman
class ConfigContext
extend Forwardable
attr_reader :app
# Whitelist methods that can reach out.
def_delegators :@app, :config, :logger, :use, :map, :mime_type, :files, :root, :build?, :server?, :environment?, :extensions
def_delegator :"@app.extensions", :activate
def initialize(app, template_context_class)
@app = app
@template_context_class = template_context_class
@callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [:before_build, :after_build, :configure, :after_configuration, :ready])
# Trigger internal callbacks when app level are executed.
app.subscribe_to_callbacks(&method(:execute_callbacks))
end
def include(mod)
extend(mod)
end
def helpers(*helper_modules, &block)
helper_modules ||= []
if block_given?
block_module = Module.new
block_module.module_eval(&block)
helper_modules << block_module
end
helper_modules.each do |mod|
@template_context_class.send :include, mod
end
end
def include_environment(name)
path = File.dirname(__FILE__)
other_config = File.join(path, name.to_s)
return unless File.exist? other_config
instance_eval File.read(other_config), other_config, 1
end
def set(key, default=nil, &block)
config.define_setting(key, default) unless config.defines_setting?(key)
@app.config[key] = block_given? ? block : default
end
# Add a new mime-type for a specific extension
#
# @param [Symbol] type File extension
# @param [String] value Mime type
# @return [void]
def mime_type(type, value)
type = ".#{type}" unless type.to_s[0] == '.'
::Rack::Mime::MIME_TYPES[type] = value
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util.rb | middleman-core/lib/middleman-core/util.rb | if RUBY_VERSION < "3.2"
require "active_support/version"
require "logger" if ActiveSupport.version < Gem::Version.new("8.0.0")
end
require 'active_support/all'
require 'middleman-core/application'
require 'middleman-core/sources'
require 'middleman-core/sitemap/resource'
require 'middleman-core/util/binary'
require 'middleman-core/util/data'
require 'middleman-core/util/files'
require 'middleman-core/util/paths'
require 'middleman-core/util/rack'
require 'middleman-core/util/uri_templates'
module Middleman
module Util
module_function
# Facade for ActiveSupport/Notification
def instrument(name, payload={}, &block)
suffixed_name = name =~ /\.middleman$/ ? name.dup : "#{name}.middleman"
::ActiveSupport::Notifications.instrument(suffixed_name, payload, &block)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/data.rb | middleman-core/lib/middleman-core/util/data.rb | require 'yaml'
require 'json'
require 'toml'
require 'pathname'
require 'hashie'
require 'memoist'
require 'middleman-core/util/binary'
require 'middleman-core/contracts'
module Middleman
module Util
include Contracts
module_function
class EnhancedHash < ::Hashie::Mash
# include ::Hashie::Extensions::MergeInitializer
# include ::Hashie::Extensions::MethodReader
# include ::Hashie::Extensions::IndifferentAccess
end
# Recursively convert a normal Hash into a EnhancedHash
#
# @private
# @param [Hash] data Normal hash
# @return [Hash]
Contract Any => Maybe[Or[Array, EnhancedHash]]
def recursively_enhance(obj)
if obj.is_a? ::Array
obj.map { |e| recursively_enhance(e) }
elsif obj.is_a? ::Hash
EnhancedHash.new(obj)
else
obj
end
end
module Data
extend Memoist
include Contracts
module_function
# Get the frontmatter and plain content from a file
# @param [String] path
# @return [Array<Hash, String>]
Contract IsA['Middleman::SourceFile'], Maybe[Symbol] => [Hash, Maybe[String]]
def parse(file, frontmatter_delims, known_type=nil)
full_path = file[:full_path]
return [{}, nil] if ::Middleman::Util.binary?(full_path) || file[:types].include?(:binary)
# Avoid weird race condition when a file is renamed
begin
content = file.read
rescue EOFError, IOError, ::Errno::ENOENT
return [{}, nil]
end
match = build_regex(frontmatter_delims).match(content) || {}
unless match[:frontmatter]
case known_type
when :yaml
return [parse_yaml(content, full_path), nil]
when :json
return [parse_json(content, full_path), nil]
when :toml
return [parse_toml(content, full_path), nil]
end
end
case [match[:start], match[:stop]]
when *frontmatter_delims[:yaml]
[
parse_yaml(match[:frontmatter], full_path),
match[:additional_content]
]
when *frontmatter_delims[:json]
[
parse_json("{#{match[:frontmatter]}}", full_path),
match[:additional_content]
]
when *frontmatter_delims[:toml]
[
parse_toml(match[:frontmatter], full_path),
match[:additional_content]
]
else
[
{},
content
]
end
end
def build_regex(frontmatter_delims)
start_delims, stop_delims = frontmatter_delims
.values
.flatten(1)
.transpose
.map(&::Regexp.method(:union))
/
\A(?:[^\r\n]*coding:[^\r\n]*\r?\n)?
(?<start>#{start_delims})[ ]*\r?\n
(?<frontmatter>.*?)[ ]*\r?\n?
^(?<stop>#{stop_delims})[ ]*\r?\n?
\r?\n?
(?<additional_content>.*)
/mx
end
memoize :build_regex
# Parse YAML frontmatter out of a string
# @param [String] content
# @return [Hash]
Contract String, Pathname => Hash
def parse_yaml(content, full_path)
permitted_classes = [Date, Time, DateTime, Symbol, Regexp]
c = begin
::Middleman::Util.instrument 'parse.yaml' do
allowed_parameters = ::YAML.method(:safe_load).parameters
if allowed_parameters.include? [:key, :permitted_classes]
::YAML.safe_load(content, permitted_classes: permitted_classes, aliases: true)
elsif allowed_parameters.include? [:key, :whitelist_classes]
::YAML.safe_load(content, whitelist_classes: permitted_classes, aliases: true)
else
::YAML.safe_load(content, permitted_classes, [], true)
end
end
rescue StandardError, ::Psych::SyntaxError => error
warn "YAML Exception parsing #{full_path}: #{error.message}"
{}
end
c ? symbolize_recursive(c) : {}
end
memoize :parse_yaml
# Parse TOML frontmatter out of a string
# @param [String] content
# @return [Hash]
Contract String, Pathname => Hash
def parse_toml(content, full_path)
c = begin
::Middleman::Util.instrument 'parse.toml' do
::TOML.load(content)
end
rescue StandardError
# TOML parser swallows useful error, so we can't warn about it.
# https://github.com/jm/toml/issues/47
warn "TOML Exception parsing #{full_path}"
{}
end
c ? symbolize_recursive(c) : {}
end
memoize :parse_yaml
# Parse JSON frontmatter out of a string
# @param [String] content
# @return [Hash]
Contract String, Pathname => Hash
def parse_json(content, full_path)
c = begin
::Middleman::Util.instrument 'parse.json' do
::JSON.parse(content)
end
rescue StandardError => error
warn "JSON Exception parsing #{full_path}: #{error.message}"
{}
end
c ? symbolize_recursive(c) : {}
end
memoize :parse_json
def symbolize_recursive(value)
case value
when Hash
value.map do |k, v|
key = k.is_a?(String) ? k.to_sym : k
[key, symbolize_recursive(v)]
end.to_h
when Array
value.map { |v| symbolize_recursive(v) }
else
value
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/files.rb | middleman-core/lib/middleman-core/util/files.rb | require 'set'
module Middleman
module Util
include Contracts
module_function
# Get a recusive list of files inside a path.
# Works with symlinks.
#
# @param path Some path string or Pathname
# @param ignore A proc/block that returns true if a given path should be ignored - if a path
# is ignored, nothing below it will be searched either.
# @return [Array<Pathname>] An array of Pathnames for each file (no directories)
Contract Or[String, Pathname], Proc => ArrayOf[Pathname]
def all_files_under(path, &ignore)
path = Pathname(path)
if ignore && yield(path)
[]
elsif path.directory?
path.children.flat_map do |child|
all_files_under(child, &ignore)
end.compact
elsif path.file?
[path]
else
[]
end
end
# Glob a directory and try to keep path encoding consistent.
#
# @param [String] path The glob path.
# @return [Array<String>]
def glob_directory(path)
results = ::Dir[path]
return results unless RUBY_PLATFORM =~ /darwin/
results.map { |r| r.encode('UTF-8', 'UTF-8-MAC') }
end
# Get the PWD and try to keep path encoding consistent.
#
# @param [String] path The glob path.
# @return [Array<String>]
def current_directory
result = ::Dir.pwd
return result unless RUBY_PLATFORM =~ /darwin/
result.encode('UTF-8', 'UTF-8-MAC')
end
Contract String => String
def step_through_extensions(path)
while ::Middleman::Util.tilt_class(path)
ext = ::File.extname(path)
break if ext.empty?
yield ext if block_given?
# Strip templating extensions as long as Tilt knows them
path = path[0..-(ext.length + 1)]
end
yield ::File.extname(path) if block_given?
path
end
# Removes the templating extensions, while keeping the others
# @param [String] path
# @return [String]
Contract String => String
def remove_templating_extensions(path)
step_through_extensions(path)
end
# Removes the templating extensions, while keeping the others
# @param [String] path
# @return [String]
Contract String => ArrayOf[String]
def collect_extensions(path)
@@extensions_cache ||= {}
base_name = ::File.basename(path)
@@extensions_cache[base_name] ||= begin
result = []
unless base_name.start_with?('.')
step_through_extensions(base_name) { |e| result << e }
end
result
end
end
# Finds files which should also be considered to be dirty when
# the given file(s) are touched.
#
# @param [Middleman::Application] app The app.
# @param [Pathname] files The original touched file paths.
# @return [Middleman::SourceFile] All related file paths, not including the source file paths.
Contract ::Middleman::Application, ArrayOf[Pathname] => ArrayOf[::Middleman::SourceFile]
def find_related_files(app, files)
return [] if files.empty?
file_set = ::Set.new(files)
all_extensions = files.flat_map { |f| collect_extensions(f.to_s) }
sass_type_aliasing = ['.scss', '.sass']
erb_type_aliasing = ['.erb', '.haml', '.slim']
all_extensions |= sass_type_aliasing unless (all_extensions & sass_type_aliasing).empty?
all_extensions |= erb_type_aliasing unless (all_extensions & erb_type_aliasing).empty?
all_extensions.uniq!
app.sitemap.resources.select { |r|
if r.file_descriptor
local_extensions = collect_extensions(r.file_descriptor[:full_path].to_s)
local_extensions |= sass_type_aliasing unless (local_extensions & sass_type_aliasing).empty?
local_extensions |= erb_type_aliasing unless (local_extensions & erb_type_aliasing).empty?
local_extensions.uniq!
!(all_extensions & local_extensions).empty? && !file_set.include?(r.file_descriptor[:full_path])
else
false
end
}.map(&:file_descriptor)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/binary.rb | middleman-core/lib/middleman-core/util/binary.rb | # Template and Mime detection
require 'tilt'
require 'rack/mime'
require 'middleman-core/contracts'
module Middleman
module Util
include Contracts
module_function
# Whether the source file is binary.
#
# @param [String] filename The file to check.
# @return [Boolean]
Contract Or[String, Pathname] => Bool
def binary?(filename)
@binary_cache ||= {}
return @binary_cache[filename] if @binary_cache.key?(filename)
@binary_cache[filename] = begin
path = Pathname(filename)
ext = path.extname
# We hardcode detecting of gzipped SVG files
if ext == '.svgz'
true
elsif ::Tilt.registered?(ext.sub('.', ''))
false
else
dot_ext = ext.to_s[0] == '.' ? ext.dup : ".#{ext}"
if mime = ::Rack::Mime.mime_type(dot_ext, nil)
!nonbinary_mime?(mime)
else
file_contents_include_binary_bytes?(path.to_s)
end
end
end
end
# Is mime type known to be non-binary?
#
# @param [String] mime The mimetype to check.
# @return [Boolean]
Contract String => Bool
def nonbinary_mime?(mime)
if mime.start_with?('text/')
true
elsif mime.include?('xml') && !mime.include?('officedocument')
true
elsif mime.include?('json')
true
elsif mime.include?('javascript')
true
else
false
end
end
# Read a few bytes from the file and see if they are binary.
#
# @param [String] filename The file to check.
# @return [Boolean]
Contract String => Bool
def file_contents_include_binary_bytes?(filename)
binary_bytes = [0, 1, 2, 3, 4, 5, 6, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 28, 29, 30, 31]
s = ::File.read(filename, 4096) || ''
s.each_byte do |c|
return true if binary_bytes.include?(c)
end
false
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/uri_templates.rb | middleman-core/lib/middleman-core/util/uri_templates.rb | # For URI templating
require 'addressable/uri'
require 'addressable/template'
require 'active_support/inflector'
require 'active_support/inflector/transliterate'
module Middleman
module Util
# Handy methods for dealing with URI templates. Mix into whatever class.
module UriTemplates
module_function
# Given a URI template string, make an Addressable::Template
# This supports the legacy middleman-blog/Sinatra style :colon
# URI templates as well as RFC6570 templates.
#
# @param [String] tmpl_src URI template source
# @return [Addressable::Template] a URI template
def uri_template(tmpl_src)
# Support the RFC6470 templates directly if people use them
if tmpl_src.include?(':')
tmpl_src = tmpl_src.gsub(/:([A-Za-z0-9]+)/, '{\1}')
end
::Addressable::Template.new(::Middleman::Util.normalize_path(tmpl_src))
end
# Apply a URI template with the given data, producing a normalized
# Middleman path.
#
# @param [Addressable::Template] template
# @param [Hash] data
# @return [String] normalized path
def apply_uri_template(template, data)
::Middleman::Util.normalize_path(::Addressable::URI.unencode(template.expand(data)).to_s)
end
# Use a template to extract parameters from a path, and validate some special (date)
# keys. Returns nil if the special keys don't match.
#
# @param [Addressable::Template] template
# @param [String] path
def extract_params(template, path)
template.extract(path, BlogTemplateProcessor)
end
# Parameterize a string preserving any multibyte characters
def safe_parameterize(str)
sep = '-'
# Reimplementation of http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-parameterize that preserves un-transliterate-able multibyte chars.
parameterized_string = ::ActiveSupport::Inflector.transliterate(str.to_s).downcase
parameterized_string.gsub!(/[^a-z0-9\-_\?]+/, sep)
parameterized_string.chars.to_a.each_with_index do |char, i|
next unless char == '?' && str[i].bytes.count != 1
parameterized_string[i] = str[i]
end
re_sep = ::Regexp.escape(sep)
# No more than one of the separator in a row.
parameterized_string.gsub!(/#{re_sep}{2,}/, sep)
# Remove leading/trailing separator.
parameterized_string.gsub!(/^#{re_sep}|#{re_sep}$/, '')
parameterized_string
end
# Convert a date into a hash of components to strings
# suitable for using in a URL template.
# @param [DateTime] date
# @return [Hash] parameters
def date_to_params(date)
{
year: date.year.to_s,
month: date.month.to_s.rjust(2, '0'),
day: date.day.to_s.rjust(2, '0')
}
end
end
# A special template processor that validates date fields
# and has an extra-permissive default regex.
#
# See https://github.com/sporkmonger/addressable/blob/master/lib/addressable/template.rb#L279
class BlogTemplateProcessor
def self.match(name)
case name
when 'year' then '\d{4}'
when 'month' then '\d{2}'
when 'day' then '\d{2}'
else '.*?'
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/rack.rb | middleman-core/lib/middleman-core/util/rack.rb | require 'middleman-core/contracts'
module Middleman
module Util
include Contracts
module_function
# Extract the text of a Rack response as a string.
# Useful for extensions implemented as Rack middleware.
# @param response The response from #call
# @return [String] The whole response as a string.
Contract RespondTo[:each] => String
def extract_response_text(response)
# The rack spec states all response bodies must respond to each
result = ''
response.each do |part, _|
result << part
end
result
end
Contract String, String, ArrayOf[String], IsA['::Middleman::Application'], Proc => String
def rewrite_paths(body, path, exts, app, &_block)
matcher = /([\'\"\(,]\s*|# sourceMappingURL=)([^\s\'\"\)\(>]+(#{::Regexp.union(exts)}))/
url_fn_prefix = 'url('
body.dup.gsub(matcher) do |match|
opening_character = $1
asset_path = $2
if asset_path.start_with?(url_fn_prefix)
opening_character << url_fn_prefix
asset_path = asset_path[url_fn_prefix.length..-1]
end
current_resource = app.sitemap.find_resource_by_destination_path(path)
begin
uri = ::Middleman::Util.parse_uri(asset_path)
if uri.relative? && uri.host.nil? && !(asset_path =~ /^[^\/].*[a-z]+\.[a-z]+\/.*/)
dest_path = ::Middleman::Util.url_for(app, asset_path, relative: false, current_resource: current_resource)
resource = app.sitemap.find_resource_by_destination_path(dest_path)
if resource && (result = yield(asset_path))
"#{opening_character}#{result}"
else
match
end
else
match
end
rescue ::Addressable::URI::InvalidURIError
match
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/util/paths.rb | middleman-core/lib/middleman-core/util/paths.rb | # Core Pathname library used for traversal
require 'pathname'
require 'uri'
require 'addressable/uri'
require 'memoist'
require 'tilt'
require 'middleman-core/contracts'
module Middleman
module Util
extend Memoist
include Contracts
module_function
Contract String => ::Addressable::URI
def parse_uri(uri)
::Addressable::URI.parse(uri)
end
memoize :parse_uri
Contract String => Any
def tilt_class(path)
::Tilt[path]
rescue LoadError
nil
end
memoize :tilt_class
# Normalize a path to not include a leading slash
# @param [String] path
# @return [String]
Contract String => String
def normalize_path(path)
# The tr call works around a bug in Ruby's Unicode handling
Addressable::URI.unencode(path).sub(%r{^/}, '').tr('', '')
end
memoize :normalize_path
# This is a separate method from normalize_path in case we
# change how we normalize paths
Contract String => String
def strip_leading_slash(path)
path.sub(%r{^/}, '')
end
memoize :strip_leading_slash
IGNORE_DESCRIPTOR = Or[Regexp, RespondTo[:call], String]
Contract IGNORE_DESCRIPTOR, String => Bool
def should_ignore?(validator, value)
if validator.is_a? Regexp
# Treat as Regexp
!!(value =~ validator)
elsif validator.respond_to? :call
# Treat as proc
validator.call(value)
elsif validator.is_a? String
# Treat as glob
File.fnmatch(value, validator)
else
# If some unknown thing, don't ignore
false
end
end
memoize :should_ignore?
# Get the path of a file of a given type
#
# @param [Middleman::Application] app The app.
# @param [Symbol] kind The type of file
# @param [String, Symbol] source The path to the file
# @param [Hash] options Data to pass through.
# @return [String]
Contract ::Middleman::Application, Symbol, Or[String, Symbol], Hash => String
def asset_path(app, kind, source, options={})
return source if source.to_s.include?('//') || source.to_s.start_with?('data:')
asset_folder = case kind
when :css
app.config[:css_dir]
when :js
app.config[:js_dir]
when :images
app.config[:images_dir]
when :fonts
app.config[:fonts_dir]
else
kind.to_s
end
source = source.to_s.tr(' ', '')
ignore_extension = (kind == :images || kind == :fonts) # don't append extension
source << ".#{kind}" unless ignore_extension || source.end_with?(".#{kind}")
asset_folder = '' if source.start_with?('/') # absolute path
asset_url(app, source, asset_folder, options)
end
# Get the URL of an asset given a type/prefix
#
# @param [String] path The path (such as "photo.jpg")
# @param [String] prefix The type prefix (such as "images")
# @param [Hash] options Data to pass through.
# @return [String] The fully qualified asset url
Contract ::Middleman::Application, String, String, Hash => String
def asset_url(app, path, prefix='', options={})
# Don't touch assets which already have a full path
return path if path.include?('//') || path.start_with?('data:')
if options[:relative] && !options[:current_resource]
raise ArgumentError, '#asset_url must be run in a context with current_resource if relative: true'
end
uri = ::Middleman::Util.parse_uri(path)
path = uri.path
# Ensure the url we pass into find_resource_by_destination_path is not a
# relative path, since it only takes absolute url paths.
dest_path = url_for(app, path, options.merge(relative: false))
result = if resource = app.sitemap.find_resource_by_path(dest_path)
resource.url
elsif resource = app.sitemap.find_resource_by_destination_path(dest_path)
resource.url
else
path = ::File.join(prefix, path)
if resource = app.sitemap.find_resource_by_path(path)
resource.url
else
::File.join(app.config[:http_prefix], path)
end
end
final_result = ::Addressable::URI.encode(
relative_path_from_resource(
options[:current_resource],
result,
options[:relative]
)
)
result_uri = ::Middleman::Util.parse_uri(final_result)
result_uri.query = uri.query
result_uri.fragment = uri.fragment
result_uri.to_s
end
# Given a source path (referenced either absolutely or relatively)
# or a Resource, this will produce the nice URL configured for that
# path, respecting :relative_links, directory indexes, etc.
Contract ::Middleman::Application, Or[String, Symbol, ::Middleman::Sitemap::Resource], Hash => String
def url_for(app, path_or_resource, options={})
if path_or_resource.is_a?(String) || path_or_resource.is_a?(Symbol)
r = app.sitemap.find_resource_by_page_id(path_or_resource)
path_or_resource = r ? r : path_or_resource.to_s
end
# Handle Resources and other things which define their own url method
url = if path_or_resource.respond_to?(:url)
path_or_resource.url
else
path_or_resource.dup
end
# Try to parse URL
begin
uri = ::Middleman::Util.parse_uri(url)
rescue ::Addressable::URI::InvalidURIError
# Nothing we can do with it, it's not really a URI
return url
end
relative = options[:relative]
raise "Can't use the relative option with an external URL" if relative && uri.host
# Allow people to turn on relative paths for all links with
# set :relative_links, true
# but still override on a case by case basis with the :relative parameter.
effective_relative = relative || false
effective_relative = true if relative.nil? && app.config[:relative_links]
# Try to find a sitemap resource corresponding to the desired path
this_resource = options[:current_resource]
if path_or_resource.is_a?(::Middleman::Sitemap::Resource)
resource = path_or_resource
resource_url = url
elsif this_resource && uri.path && !uri.host
# Handle relative urls
url_path = Pathname(uri.path)
current_source_dir = Pathname('/' + this_resource.path).dirname
url_path = current_source_dir.join(url_path) if url_path.relative?
resource = app.sitemap.find_resource_by_path(url_path.to_s)
if resource
resource_url = resource.url
else
# Try to find a resource relative to destination paths
url_path = Pathname(uri.path)
current_source_dir = Pathname('/' + this_resource.destination_path).dirname
url_path = current_source_dir.join(url_path) if url_path.relative?
resource = app.sitemap.find_resource_by_destination_path(url_path.to_s)
resource_url = resource.url if resource
end
elsif options[:find_resource] && uri.path && !uri.host
resource = app.sitemap.find_resource_by_path(uri.path)
resource_url = resource.url if resource
end
if resource
uri.path = if this_resource
::Addressable::URI.encode(
relative_path_from_resource(
this_resource,
resource_url,
effective_relative
)
)
else
resource_url
end
end
# Support a :query option that can be a string or hash
if query = options[:query]
uri.query = query.respond_to?(:to_param) ? query.to_param : query.to_s
end
# Support a :fragment or :anchor option just like Padrino
fragment = options[:anchor] || options[:fragment]
uri.fragment = fragment.to_s if fragment
# Finally make the URL back into a string
uri.to_s
end
# Expand a path to include the index file if it's a directory
#
# @param [String] path Request path/
# @param [Middleman::Application] app The requesting app.
# @return [String] Path with index file if necessary.
Contract String, ::Middleman::Application => String
def full_path(path, app)
resource = app.sitemap.find_resource_by_destination_path(path)
unless resource
# Try it with /index.html at the end
indexed_path = ::File.join(path.sub(%r{/$}, ''), app.config[:index_file])
resource = app.sitemap.find_resource_by_destination_path(indexed_path)
end
if resource
'/' + resource.destination_path
else
'/' + normalize_path(path)
end
end
# Get a relative path to a resource.
#
# @param [Middleman::Sitemap::Resource] curr_resource The resource.
# @param [String] resource_url The target url.
# @param [Boolean] relative If the path should be relative.
# @return [String]
Contract ::Middleman::Sitemap::Resource, String, Bool => String
def relative_path_from_resource(curr_resource, resource_url, relative)
# Switch to the relative path between resource and the given resource
# if we've been asked to.
if relative
# Output urls relative to the destination path, not the source path
current_dir = Pathname('/' + curr_resource.destination_path).dirname
relative_path = Pathname(resource_url).relative_path_from(current_dir).to_s
# Put back the trailing slash to avoid unnecessary Apache redirects
if resource_url.end_with?('/') && !relative_path.end_with?('/')
relative_path << '/'
end
relative_path
else
resource_url
end
end
# Takes a matcher, which can be a literal string
# or a string containing glob expressions, or a
# regexp, or a proc, or anything else that responds
# to #match or #call, and returns whether or not the
# given path matches that matcher.
#
# @param [String, #match, #call] matcher A matcher String, RegExp, Proc, etc.
# @param [String] path A path as a string
# @return [Boolean] Whether the path matches the matcher
Contract PATH_MATCHER, String => Bool
def path_match(matcher, path)
if matcher.is_a?(String)
if matcher.include? '*'
::File.fnmatch(matcher, path)
else
path == matcher
end
elsif matcher.respond_to?(:match)
!!(path =~ matcher)
elsif matcher.respond_to?(:call)
matcher.call(path)
else
::File.fnmatch(matcher.to_s, path)
end
end
memoize :path_match
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/sources/source_watcher.rb | middleman-core/lib/middleman-core/sources/source_watcher.rb | # Watcher Library
require 'listen'
require 'middleman-core/contracts'
require 'digest'
require 'set'
# Monkey patch Listen silencer so `only` works on directories too
module Listen
class Silencer
# TODO: switch type and path places - and verify
def silenced?(relative_path, _type)
path = relative_path.to_s
# if only_patterns && type == :file
# return true unless only_patterns.any? { |pattern| path =~ pattern }
# end
return !only_patterns.any? { |pattern| path =~ pattern } if only_patterns
ignore_patterns.any? { |pattern| path =~ pattern }
end
end
end
module Middleman
# The default source watcher implementation. Watches a directory on disk
# and responds to events on changes.
class SourceWatcher
extend Forwardable
include Contracts
# References to parent `Sources` app and `globally_ignored?` check.
def_delegators :@parent, :app, :globally_ignored?
# Reference to the singleton logger
def_delegator :app, :logger
# The type this watcher is representing
Contract Symbol
attr_reader :type
# The directory that is being watched
Contract Pathname
attr_reader :directory
# Options for configuring the watcher
Contract Hash
attr_reader :options
# Reference to lower level listener
attr_reader :listener
IGNORED_DIRECTORIES = Set.new(%w(.git node_modules .sass-cache vendor/bundle .bundle))
# Construct a new SourceWatcher
#
# @param [Middleman::Sources] parent The parent collection.
# @param [Symbol] type The watcher type.
# @param [String] directory The on-disk path to watch.
# @param [Hash] options Configuration options.
Contract IsA['Middleman::Sources'], Symbol, String, Hash => Any
def initialize(parent, type, directory, options={})
@parent = parent
@options = options
@type = type
@directory = Pathname(directory)
@files = {}
@extensionless_files = {}
@frontmatter = options.fetch(:frontmatter, true)
@binary = options.fetch(:binary, false)
@validator = options.fetch(:validator, proc { true })
@ignored = options.fetch(:ignored, proc { false })
@only = Array(options.fetch(:only, []))
@disable_watcher = app.build?
@force_polling = false
@latency = nil
@wait_for_delay = nil
@listener = nil
@callbacks = ::Middleman::CallbackManager.new
@callbacks.install_methods!(self, [:on_change])
@waiting_for_existence = !@directory.exist?
end
# Change the path of the watcher (if config values upstream change).
#
# @param [String] directory The new path.
# @return [void]
Contract String => Any
def update_path(directory)
@directory = Pathname(File.expand_path(directory, app.root))
without_listener_running do
update([], @files.values.map { |source_file| source_file[:full_path] })
end
poll_once!
end
def update_config(options={})
without_listener_running do
@disable_watcher = options.fetch(:disable_watcher, false)
@force_polling = options.fetch(:force_polling, false)
@latency = options.fetch(:latency, nil)
@wait_for_delay = options.fetch(:wait_for_delay, nil)
end
end
# Stop watching.
#
# @return [void]
Contract Any
def unwatch
stop_listener!
end
# All the known files in this watcher.
#
# @return [Array<Middleman::SourceFile>]
Contract ArrayOf[IsA['Middleman::SourceFile']]
def files
@files.values
end
# Find a specific file in this watcher.
#
# @param [String, Pathname] path The search path.
# @param [Boolean] glob If the path contains wildcard characters.
# @return [Middleman::SourceFile, nil]
Contract Or[String, Pathname], Maybe[Bool] => Maybe[IsA['Middleman::SourceFile']]
def find(path, glob=false)
path = path.to_s.encode!('UTF-8', 'UTF-8-MAC') if RUBY_PLATFORM =~ /darwin/
p = Pathname(path)
return nil if p.absolute? && !p.to_s.start_with?(@directory.to_s)
p = @directory + p if p.relative?
if glob
@extensionless_files[p]
else
@files[p]
end
end
# Check if a file simply exists in this watcher.
#
# @param [String, Pathname] path The search path.
# @return [Boolean]
Contract Or[String, Pathname] => Bool
def exists?(path)
!find(path).nil?
end
# Start the `listen` gem Listener.
#
# @return [void]
Contract Any
def listen!
return if @disable_watcher || @listener || @waiting_for_existence
config = {
force_polling: @force_polling
}
config[:wait_for_delay] = @wait_for_delay.try(:to_f) || 0.5
config[:latency] = @latency.to_f if @latency
@listener = ::Listen.to(@directory.to_s, config, &method(:on_listener_change))
@listener.ignore(/^\.sass-cache/)
@listener.ignore(/^node_modules/)
@listener.ignore(/^vendor\/bundle/)
@listener.start
end
# Stop the listener.
#
# @return [void]
Contract Any
def stop_listener!
return unless @listener
@listener.stop
@listener = nil
end
Contract ArrayOf[Pathname]
def find_new_files!
new_files = ::Middleman::Util.all_files_under(@directory.to_s, &method(:should_not_recurse?))
.reject { |p| @files.key?(p) }
update(new_files, []).flatten.map { |s| s[:full_path] }
end
# Manually trigger update events.
#
# @return [void]
Contract ArrayOf[Pathname]
def poll_once!
updated = ::Middleman::Util.all_files_under(@directory.to_s, &method(:should_not_recurse?))
removed = @files.keys - updated
result = update(updated, removed)
if @waiting_for_existence && @directory.exist?
@waiting_for_existence = false
listen!
end
result.flatten.map { |s| s[:full_path] }
end
# Work around this bug: http://bugs.ruby-lang.org/issues/4521
# where Ruby will call to_s/inspect while printing exception
# messages, which can take a long time (minutes at full CPU)
# if the object is huge or has cyclic references, like this.
def to_s
"#<Middleman::SourceWatcher:0x#{object_id} type=#{@type.inspect} directory=#{@directory.inspect}>"
end
alias inspect to_s # Ruby 2.0 calls inspect for NoMethodError instead of to_s
protected
Contract Pathname => Bool
def should_not_recurse?(p)
relative_path = p.relative_path_from(@directory).to_s
IGNORED_DIRECTORIES.include?(relative_path)
end
# The `listen` gem callback.
#
# @param [Array] modified List of modified files.
# @param [Array] added List of added files.
# @param [Array] removed List of removed files.
# @return [void]
Contract Array, Array, Array => Any
def on_listener_change(modified, added, removed)
updated = (modified + added)
return if updated.empty? && removed.empty?
update(updated.map { |s| Pathname(s) }, removed.map { |s| Pathname(s) })
end
# Update our internal list of files on a change.
#
# @param [String, Pathname] path The updated file path.
# @return [void]
Contract ArrayOf[Pathname], ArrayOf[Pathname] => ArrayOf[ArrayOf[IsA['Middleman::SourceFile']]]
def update(updated_paths, removed_paths)
valid_updates = updated_paths
.map { |p| @files[p] || path_to_source_file(p, @directory, @type, @options[:destination_dir]) }
.select(&method(:valid?))
valid_updates.each do |f|
record_file_change(f)
logger.debug "== Change (#{f[:types].inspect}): #{f[:relative_path]}"
end
related_sources = valid_updates.map { |u| u[:full_path] } + removed_paths
related_updates = ::Middleman::Util.find_related_files(app, related_sources).select(&method(:valid?))
related_updates.each do |f|
logger.debug "== Possible Change (#{f[:types].inspect}): #{f[:relative_path]}"
end
valid_updates |= related_updates
valid_removes = removed_paths
.select(&@files.method(:key?))
.map(&@files.method(:[]))
.select(&method(:valid?))
.each do |f|
remove_file_from_cache(f)
logger.debug "== Deletion (#{f[:types].inspect}): #{f[:relative_path]}"
end
unless valid_updates.empty? && valid_removes.empty?
execute_callbacks(:on_change, [
valid_updates,
valid_removes,
self
])
end
[valid_updates, valid_removes]
end
# Convert a path to a file resprentation.
#
# @param [Pathname] path The path.
# @return [Middleman::SourceFile]
Contract Pathname, Pathname, Symbol, Maybe[String] => ::Middleman::SourceFile
def path_to_source_file(path, directory, type, destination_dir)
types = Set.new([type])
types << :no_frontmatter unless @frontmatter
types << :binary if @binary
relative_path = path.relative_path_from(directory)
relative_path = File.join(destination_dir, relative_path) if destination_dir
types << :no_frontmatter if partial?(relative_path.to_s)
::Middleman::SourceFile.new(Pathname(relative_path), path, directory, types, 0)
end
def partial?(relative_path)
relative_path.split(::File::SEPARATOR).any? { |p| p.start_with?('_') }
end
Contract IsA['Middleman::SourceFile'] => Any
def record_file_change(f)
if @files[f[:full_path]]
@files[f[:full_path]][:version] += 1
else
@files[f[:full_path]] = f
@extensionless_files[strip_extensions(f[:full_path])] = f
end
end
Contract IsA['Middleman::SourceFile'] => Any
def remove_file_from_cache(f)
@files.delete(f[:full_path])
@extensionless_files.delete(strip_extensions(f[:full_path]))
end
Contract Pathname => Pathname
def strip_extensions(p)
p = p.sub_ext('') while Middleman::Util.tilt_class(p.to_s) || p.extname == '.html'
Pathname(p.to_s + '.*')
end
# Check if this watcher should care about a file.
#
# @param [Middleman::SourceFile] file The file.
# @return [Boolean]
Contract IsA['Middleman::SourceFile'] => Bool
def valid?(file)
return false unless @validator.call(file) && !globally_ignored?(file)
if @only.empty?
!@ignored.call(file)
else
@only.any? { |reg| file[:relative_path].to_s =~ reg }
end
end
private
def without_listener_running
listener_running = @listener && @listener.processing?
stop_listener! if listener_running
yield
if listener_running
poll_once!
listen!
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/data.rb | middleman-core/lib/middleman-core/core_extensions/data.rb | require 'middleman-core/contracts'
require 'middleman-core/util/data'
module Middleman
module CoreExtensions
# The data extension parses YAML and JSON files in the `data/` directory
# and makes them available to `config.rb`, templates and extensions
class Data < Extension
attr_reader :data_store
define_setting :data_dir, ENV['MM_DATA_DIR'] || 'data', 'The directory data files are stored in'
# Make the internal `data_store` method available as `app.data`
expose_to_application data: :data_store
# Exposes `data` to templates
expose_to_template data: :data_store
# The regex which tells Middleman which files are for data
DATA_FILE_MATCHER = /^(.*?)[\w-]+\.(yml|yaml|json|toml)$/
def initialize(app, config={}, &block)
super
@data_store = DataStore.new(app, DATA_FILE_MATCHER)
start_watching(app.config[:data_dir])
end
def start_watching(dir)
@original_data_dir = dir
# Tell the file watcher to observe the :data_dir
@watcher = app.files.watch :data,
path: File.join(app.root, dir),
only: DATA_FILE_MATCHER
# Setup data files before anything else so they are available when
# parsing config.rb
app.files.on_change(:data, &@data_store.method(:update_files))
end
def after_configuration
return unless @original_data_dir != app.config[:data_dir]
@watcher.update_path(app.config[:data_dir])
end
# The core logic behind the data extension.
class DataStore
include Contracts
# Setup data store
#
# @param [Middleman::Application] app The current instance of Middleman
def initialize(app, data_file_matcher)
@app = app
@data_file_matcher = data_file_matcher
@local_data = {}
@local_data_enhanced = nil
@local_sources = {}
@callback_sources = {}
end
# Store static data hash
#
# @param [Symbol] name Name of the data, used for namespacing
# @param [Hash] content The content for this data
# @return [Hash]
Contract Symbol, Or[Hash, Array] => Hash
def store(name=nil, content=nil)
@local_sources[name.to_s] = content unless name.nil? || content.nil?
@local_sources
end
# Store callback-based data
#
# @param [Symbol] name Name of the data, used for namespacing
# @param [Proc] proc The callback which will return data
# @return [Hash]
Contract Maybe[Symbol], Maybe[Proc] => Hash
def callbacks(name=nil, proc=nil)
@callback_sources[name.to_s] = proc unless name.nil? || proc.nil?
@callback_sources
end
Contract ArrayOf[IsA['Middleman::SourceFile']], ArrayOf[IsA['Middleman::SourceFile']] => Any
def update_files(updated_files, removed_files)
updated_files.each(&method(:touch_file))
removed_files.each(&method(:remove_file))
@app.sitemap.rebuild_resource_list!(:touched_data_file)
end
# Update the internal cache for a given file path
#
# @param [String] file The file to be re-parsed
# @return [void]
Contract IsA['Middleman::SourceFile'] => Any
def touch_file(file)
data_path = file[:relative_path]
extension = File.extname(data_path)
basename = File.basename(data_path, extension)
return unless %w(.yaml .yml .json .toml).include?(extension)
if %w(.yaml .yml).include?(extension)
data, postscript = ::Middleman::Util::Data.parse(file, @app.config[:frontmatter_delims], :yaml)
data[:postscript] = postscript if !postscript.nil? && data.is_a?(Hash)
elsif extension == '.json'
data, _postscript = ::Middleman::Util::Data.parse(file, @app.config[:frontmatter_delims], :json)
elsif extension == '.toml'
data, _postscript = ::Middleman::Util::Data.parse(file, @app.config[:frontmatter_delims], :toml)
end
data_branch = @local_data
path = data_path.to_s.split(File::SEPARATOR)[0..-2]
path.each do |dir|
data_branch[dir] ||= {}
data_branch = data_branch[dir]
end
data_branch[basename] = data
@local_data_enhanced = nil
end
# Remove a given file from the internal cache
#
# @param [String] file The file to be cleared
# @return [void]
Contract IsA['Middleman::SourceFile'] => Any
def remove_file(file)
data_path = file[:relative_path]
extension = File.extname(data_path)
basename = File.basename(data_path, extension)
data_branch = @local_data
path = data_path.to_s.split(File::SEPARATOR)[0..-2]
path.each do |dir|
data_branch = data_branch[dir]
end
data_branch.delete(basename) if data_branch.key?(basename)
@local_data_enhanced = nil
end
# Get a hash from either internal static data or a callback
#
# @param [String, Symbol] path The name of the data namespace
# @return [Hash, nil]
Contract Or[String, Symbol] => Maybe[Or[Array, IsA['Middleman::Util::EnhancedHash']]]
def data_for_path(path)
response = if store.key?(path.to_s)
store[path.to_s]
elsif callbacks.key?(path.to_s)
callbacks[path.to_s].call
end
::Middleman::Util.recursively_enhance(response)
end
# "Magically" find namespaces of data if they exist
#
# @param [String] path The namespace to search for
# @return [Hash, nil]
def method_missing(path)
if @local_data.key?(path.to_s)
# Any way to cache this?
@local_data_enhanced ||= ::Middleman::Util.recursively_enhance(@local_data)
return @local_data_enhanced[path.to_s]
else
result = data_for_path(path)
return result if result
end
super
end
# Needed so that method_missing makes sense
def respond_to?(method, include_private=false)
super || key?(method)
end
# Make DataStore act like a hash. Return requested data, or
# nil if data does not exist
#
# @param [String, Symbol] key The name of the data namespace
# @return [Hash, nil]
def [](key)
__send__(key) if key?(key)
end
def key?(key)
(@local_data.keys + @local_sources.keys + @callback_sources.keys).include?(key.to_s)
end
alias has_key? key?
# Convert all the data into a static hash
#
# @return [Hash]
Contract Hash
def to_h
data = {}
store.each_key do |k|
data[k] = data_for_path(k)
end
callbacks.each_key do |k|
data[k] = data_for_path(k)
end
(@local_data || {}).each do |k, v|
data[k] = v
end
data
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/external_helpers.rb | middleman-core/lib/middleman-core/core_extensions/external_helpers.rb | module Middleman
module CoreExtensions
# Load helpers in `helpers/`
class ExternalHelpers < Extension
define_setting :helpers_dir, 'helpers', 'Directory to autoload helper modules from'
define_setting :helpers_filename_glob, '**.rb', 'Glob pattern for matching helper ruby files'
define_setting :helpers_filename_to_module_name_proc, proc { |filename|
basename = File.basename(filename, File.extname(filename))
basename.camelcase
}, 'Proc implementing the conversion from helper filename to module name'
def after_configuration
helpers_path = File.join(app.root, app.config[:helpers_dir])
return unless File.exist?(helpers_path)
glob = File.join(helpers_path, app.config[:helpers_filename_glob])
::Middleman::Util.glob_directory(glob).each do |filename|
module_name = app.config[:helpers_filename_to_module_name_proc].call(filename)
next unless module_name
require filename
next unless Object.const_defined?(module_name.to_sym)
app.template_context_class.send :include, Object.const_get(module_name.to_sym)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/front_matter.rb | middleman-core/lib/middleman-core/core_extensions/front_matter.rb | # Core Pathname library used for traversal
require 'pathname'
# DbC
require 'middleman-core/contracts'
require 'active_support/core_ext/hash/keys'
require 'middleman-core/util/data'
# Extensions namespace
module Middleman::CoreExtensions
class FrontMatter < ::Middleman::Extension
# Try to run after routing but before directory_indexes
self.resource_list_manipulator_priority = 20
# Set textual delimiters that denote the start and end of frontmatter
define_setting :frontmatter_delims, {
json: [%w(;;; ;;;)],
toml: [%w(+++ +++)],
yaml: [%w(--- ---), %w(--- ...)]
}, 'Allowed frontmatter delimiters'
def initialize(app, options_hash={}, &block)
super
@cache = {}
end
def before_configuration
app.files.on_change(:source, &method(:clear_data))
end
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
resources.each do |resource|
next if resource.binary?
next if resource.file_descriptor.nil?
next if resource.file_descriptor[:types].include?(:no_frontmatter)
fmdata = data(resource.file_descriptor[:full_path].to_s).first.dup
# Copy over special options
# TODO: Should we make people put these under "options" instead of having
# special known keys?
opts = fmdata.extract!(:layout, :layout_engine, :renderer_options, :directory_index, :content_type)
opts[:renderer_options].symbolize_keys! if opts.key?(:renderer_options)
ignored = fmdata.delete(:ignored)
# TODO: Enhance data? NOOOO
# TODO: stringify-keys? immutable/freeze?
resource.add_metadata options: opts, page: fmdata
resource.ignore! if ignored == true && !resource.is_a?(::Middleman::Sitemap::ProxyResource)
# TODO: Save new template here somewhere?
end
end
# Get the template data from a path
# @param [String] path
# @return [String]
Contract String => Maybe[String]
def template_data_for_file(path)
data(path).last
end
Contract String => [Hash, Maybe[String]]
def data(path)
file = app.files.find(:source, path)
return [{}, nil] unless file
file_path = file[:full_path].to_s
@cache[file_path] ||= begin
::Middleman::Util::Data.parse(
file,
app.config[:frontmatter_delims]
)
end
end
Contract ArrayOf[IsA['Middleman::SourceFile']], ArrayOf[IsA['Middleman::SourceFile']] => Any
def clear_data(updated_files, removed_files)
(updated_files + removed_files).each do |file|
@cache.delete(file[:full_path].to_s)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/routing.rb | middleman-core/lib/middleman-core/core_extensions/routing.rb | # Routing extension
module Middleman
module CoreExtensions
class Routing < ConfigExtension
# This should always run late, but not as late as :directory_indexes,
# so it can add metadata to any pages generated by other extensions
self.resource_list_manipulator_priority = [10, 130]
# Expose the `page` method to config.
expose_to_config :page
PageDescriptor = Struct.new(:path, :metadata) do
def execute_descriptor(app, resources)
normalized_path = path.dup
if normalized_path.is_a?(String) && !normalized_path.include?('*')
# Normalize path
normalized_path = ::Middleman::Util.normalize_path(normalized_path)
if normalized_path.end_with?('/') || app.files.by_type(:source).watchers.any? { |w| (w.directory + Pathname(normalized_path)).directory? }
normalized_path = ::File.join(normalized_path, app.config[:index_file])
end
end
normalized_path = '/' + ::Middleman::Util.strip_leading_slash(normalized_path) if normalized_path.is_a?(String)
resources
.select { |r| ::Middleman::Util.path_match(normalized_path, "/#{r.path}") }
.each { |r| r.add_metadata(metadata, true) }
resources
end
end
# The page method allows options to be set for a given source path, regex, or glob.
# Options that may be set include layout, locals, andx ignore.
#
# @example
# page '/about.html', layout: false
# @example
# page '/index.html', layout: :homepage_layout
# @example
# page '/foo.html', locals: { foo: 'bar' }
#
# @param [String, Regexp] path A source path, or a Regexp/glob that can match multiple resources.
# @params [Hash] opts Options to apply to all matching resources. Undocumented options are passed on as page metadata to be used by extensions.
# @option opts [Symbol, Boolean, String] layout The layout name to use (e.g. `:article`) or `false` to disable layout.
# @option opts [Boolean] directory_indexes Whether or not the `:directory_indexes` extension applies to these paths.
# @option opts [Hash] locals Local variables for the template. These will be available when the template renders.
# @option opts [Hash] data Extra metadata to add to the page. This is the same as frontmatter, though frontmatter will take precedence over metadata defined here. Available via {Resource#data}.
# @return [void]
Contract Or[String, Regexp], Hash => PageDescriptor
def page(path, opts={})
options = opts.dup
page_data = options.delete(:data) || {}
page_data[:id] = options.delete(:id) if options.key?(:id)
# Default layout
metadata = {
locals: options.delete(:locals) || {},
page: page_data,
options: options
}
PageDescriptor.new(path, metadata)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/rendering.rb | middleman-core/lib/middleman-core/core_extensions/rendering.rb | require 'middleman-core/template_context'
# ERb Support
Middleman::Extensions.register :erb_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/erb'
Middleman::Renderers::ERb
end
# CoffeeScript Support
Middleman::Extensions.register :coffee_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/coffee_script'
Middleman::Renderers::CoffeeScript
end
# Haml Support
Middleman::Extensions.register :haml_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/haml'
Middleman::Renderers::Haml
end
# Sass Support
Middleman::Extensions.register :sass_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/sass'
Middleman::Renderers::Sass
end
# Markdown Support
Middleman::Extensions.register :markdown_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/markdown'
Middleman::Renderers::Markdown
end
# Liquid Support
Middleman::Extensions.register :liquid_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/liquid'
Middleman::Renderers::Liquid
end
# Slim Support
Middleman::Extensions.register :slim_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/slim'
Middleman::Renderers::Slim
end
# Less Support
Middleman::Extensions.register :less_renderer, auto_activate: :before_configuration do
require 'middleman-core/renderers/less'
Middleman::Renderers::Less
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/file_watcher.rb | middleman-core/lib/middleman-core/core_extensions/file_watcher.rb | require 'middleman-core/contracts'
require 'middleman-core/sources'
module Middleman
module CoreExtensions
# API for watching file change events
class FileWatcher < Extension
# All defined sources.
Contract IsA['Middleman::Sources']
attr_reader :sources
# Make the internal `sources` method available as `app.files`
expose_to_application files: :sources
# Make the internal `sources` method available in config as `files`
expose_to_config files: :sources
# The default list of ignores.
IGNORES = {
emacs_files: /(^|\/)\.?#/,
tilde_files: /~$/,
ds_store: /\.DS_Store$/,
git: /(^|\/)\.git(ignore|modules|\/)/
}.freeze
# Setup the extension.
def initialize(app, config={}, &block)
super
# Setup source collection.
@sources = ::Middleman::Sources.new(app)
# Add default ignores.
IGNORES.each do |key, value|
@sources.ignore key, :all, value
end
# Watch current source.
start_watching(app.config[:source])
end
# Before we config, find initial files.
#
# @return [void]
Contract Any
def before_configuration
@sources.poll_once!
end
# After we config, find new files since config can change paths.
#
# @return [void]
Contract Any
def after_configuration
@watcher.update_config(
disable_watcher: app.config[:watcher_disable],
force_polling: app.config[:watcher_force_polling],
latency: app.config[:watcher_latency],
wait_for_delay: app.config[:watcher_wait_for_delay]
)
if @original_source_dir != app.config[:source]
@watcher.update_path(app.config[:source])
end
@sources.start!
@sources.poll_once!
end
protected
# Watch the source directory.
#
# @return [void]
Contract String => Any
def start_watching(dir)
@original_source_dir = dir
@watcher = @sources.watch :source, path: File.join(app.root, dir)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/i18n.rb | middleman-core/lib/middleman-core/core_extensions/i18n.rb | class Middleman::CoreExtensions::Internationalization < ::Middleman::Extension
option :no_fallbacks, false, 'Disable I18n fallbacks'
option :locales, nil, 'List of locales, will autodiscover by default'
option :langs, nil, 'Backwards compatibility if old option name. Use `locales` instead.'
option :locale_map, {}, 'Locale shortname map'
option :lang_map, nil, 'Backwards compatibility if old option name. Use `locale_map` instead.'
option :path, '/:locale/', 'URL prefix path'
option :templates_dir, 'localizable', 'Location of templates to be localized'
option :mount_at_root, nil, 'Mount a specific locale at the root of the site'
option :data, 'locales', 'The directory holding your locale configurations'
# Exposes `locales` to templates
expose_to_template :locales, :langs, :locale, :lang
def initialize(*)
super
require 'i18n'
options[:locales] = options[:langs] unless options[:langs].nil?
options[:locale_map] = options[:lang_map] unless options[:lang_map].nil?
# Don't fail on invalid locale, that's not what our current
# users expect.
::I18n.enforce_available_locales = false
# This is for making the tests work - since the tests
# don't completely reload middleman, I18n.load_path can get
# polluted with paths from other test app directories that don't
# exist anymore.
if ENV['TEST']
app.after_configuration_eval do
::I18n.load_path.delete_if { |path| path =~ %r{tmp/aruba} }
::I18n.reload!
end
end
end
def after_configuration
# See https://github.com/svenfuchs/i18n/wiki/Fallbacks
unless options[:no_fallbacks]
require 'i18n/backend/fallbacks'
::I18n::Backend::Simple.send(:include, ::I18n::Backend::Fallbacks)
end
locales_file_path = options[:data]
# Tell the file watcher to observe the :data_dir
app.files.watch :locales,
path: File.join(app.root, locales_file_path),
only: /.*(rb|yml|yaml)$/
# Setup data files before anything else so they are available when
# parsing config.rb
app.files.on_change(:locales, &method(:on_file_changed))
@maps = {}
@mount_at_root = options[:mount_at_root].nil? ? locales.first : options[:mount_at_root]
configure_i18n
logger.info "== Locales: #{locales.join(', ')} (Default #{@mount_at_root})"
end
helpers do
def t(*args)
::I18n.t(*args)
end
def url_for(path_or_resource, options={})
locale = options.delete(:locale) || ::I18n.locale
opts = options.dup
should_relativize = opts.key?(:relative) ? opts[:relative] : config[:relative_links]
anchor = opts[:anchor]
# The first call to `super()` is only to find the correct URL. The next
# call will relativize and add the anchor.
opts[:relative] = false
opts[:anchor] = nil
href = super(path_or_resource, opts)
final_path = if result = extensions[:i18n].localized_path(href, locale)
result
else
# Should we log the missing file?
href
end
opts[:relative] = should_relativize
opts[:anchor] = anchor
begin
super(final_path, opts)
rescue RuntimeError
super(path_or_resource, options)
end
end
def locate_partial(partial_name, try_static=false)
locals_dir = extensions[:i18n].options[:templates_dir]
# Try /localizable
partials_path = File.join(locals_dir, partial_name)
locale_suffix = ::I18n.locale
extname = File.extname(partial_name)
maybe_static = !extname.empty?
suffixed_partial_name = if maybe_static
partial_name.sub(extname, ".#{locale_suffix}#{extname}")
else
"#{partial_name}.#{locale_suffix}"
end
if locale_suffix
super(suffixed_partial_name, maybe_static) ||
super(File.join(locals_dir, suffixed_partial_name), maybe_static) ||
super(partials_path, try_static) ||
super
else
super(partials_path, try_static) ||
super
end
end
end
Contract ArrayOf[Symbol]
def locales
@locales ||= known_locales
end
# Backwards API compat
alias langs locales
Contract Symbol
def locale
::I18n.locale
end
# Backwards API compat
alias lang locale
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
new_resources = []
file_extension_resources = resources.select do |resource|
# Ignore resources which are outside of the localizable directory
File.fnmatch?(File.join(options[:templates_dir], '**'), resource.path) &&
parse_locale_extension(resource.path)
end
localizable_folder_resources = resources.select do |resource|
!file_extension_resources.include?(resource) && File.fnmatch?(File.join(options[:templates_dir], '**'), resource.path)
end
# If it's a "localizable template"
localizable_folder_resources.each do |resource|
next if resource.ignored?
page_id = File.basename(resource.path, File.extname(resource.path))
locales.each do |locale|
# Remove folder name
path = resource.path.sub(options[:templates_dir], '')
new_resources << build_resource(path, resource.path, page_id, locale)
end
resource.ignore!
# This is for backwards compatibility with the old provides_metadata-based code
# that used to be in this extension, but I don't know how much sense it makes.
# next if resource.options[:locale]
# $stderr.puts "Defaulting #{resource.path} to #{@mount_at_root}"
# resource.add_metadata options: { locale: @mount_at_root }, locals: { locale: @mount_at_root }
end
# If it uses file extension localization
file_extension_resources.each do |resource|
next if resource.ignored?
result = parse_locale_extension(resource.path)
ext_locale, path, page_id = result
new_resources << build_resource(path, resource.path, page_id, ext_locale)
resource.ignore!
end
# This generates a lookup hash that maps the real path (as seen by the web
# page user) to the paths of the localized versions. The lookup is later
# used by `url_for '/some/page.html', :locale => :en` and other url
# helpers.
#
# For example (given :mount_at_root => :es) and localized paths:
#
# @lookup['/en/magic/stuff.html'] = {:en => '/en/magic/stuff.html', :de => '/de/magisches/zeug.html', :es => '/magico/cosas.html'}
# @lookup['/de/index.html'] = {:en => '/en/index.html', :de => '/de/index.html', :es => '/index.html'}
# @lookup['/en/index.html'] = {:en => '/en/index.html', :de => '/de/index.html', :es => '/index.html'}
# @lookup['/index.html'] = {:en => '/en/index.html', :de => '/de/index.html', :es => '/index.html'}
#
# We do this by grouping by the source paths with the locales removed. All
# the localized pages with the same content in different languages get the
# same key.
#
@source_path_group = new_resources.group_by do |resource|
# Try to get source path without extension
_locale, path, _page_id = parse_locale_extension(resource.source_path)
# If that fails, there is no extension, so we use the original path. We
# can not use resource.path here, because .path may be translated, so the
# file names do not match up.
path ||= resource.source_path
# This will contain the localizable/ directory, but that does not matter,
# because it will be contained in both alternatives above, so the
# grouping key will be correct.
path
end
# Then we walk this grouped hash and generate the lookup table as given
# above.
@lookup = {}
@source_path_group.each do |src_path, resources|
# For each group we generate a list of the paths the user really sees
# (e.g. ['/en/index.html', '/de/index.html', '/index.html'])
exposed_paths = resources.map(&:path)
# We also generate a map with the same infos, but with the locales as keys.
# e.g. {:en => '/en/index.html', :de => '/de/index.html', :es => '/index.html'}
locale_map = resources.each_with_object({}) do |resource, map|
map[resource.locale] = '/' + resource.path
end
# Then we add those to the lookup table, so every path has a
# cross-reference to any other path in other locales.
exposed_paths.each do |path|
@lookup['/' + path] = locale_map
end
if @mount_at_root == false
src_path = src_path.sub(options[:templates_dir] + '/', '')
@lookup["/#{src_path}"] = locale_map
end
end
new_resources.reduce(resources) do |sum, r|
r.execute_descriptor(app, sum)
end
end
Contract String, Symbol => Maybe[String]
def localized_path(path, locale)
lookup_path = path.dup
lookup_path << app.config[:index_file] if lookup_path.end_with?('/')
@lookup[lookup_path] && @lookup[lookup_path][locale]
end
Contract Symbol => String
def path_root(locale)
if (options[:mount_at_root] == locale) || (options[:mount_at_root].nil? && locales[0] == locale)
'/'
else
replacement = options[:locale_map][locale] || locale
options[:path].sub(':locale', replacement.to_s).sub(':lang', replacement.to_s) # Backward compat
end
end
private
def on_file_changed(_updated_files, _removed_files)
::I18n.load_path |= app.files.by_type(:locales).files.map { |p| p[:full_path].to_s }
::I18n.reload!
@app.sitemap.rebuild_resource_list!(:touched_locale_file)
end
def configure_i18n
::I18n.load_path |= app.files.by_type(:locales).files.map { |p| p[:full_path].to_s }
::I18n.reload!
::I18n.default_locale = @mount_at_root
# Reset fallbacks to fall back to our new default
if ::I18n.respond_to?(:fallbacks)
::I18n.fallbacks = ::I18n::Locale::Fallbacks.new(::I18n.default_locale)
end
end
Contract ArrayOf[Symbol]
def known_locales
if options[:locales]
Array(options[:locales]).map(&:to_sym)
else
known_locales = app.files.by_type(:locales).files.select do |p|
p[:relative_path].to_s.split(File::SEPARATOR).length == 1
end
known_locales.map do |p|
File.basename(p[:relative_path].to_s).sub(/\.ya?ml$/, '').sub(/\.rb$/, '')
end.sort.map(&:to_sym)
end
end
# Parse locale extension filename
# @return [locale, path, basename]
# will return +nil+ if no locale extension
Contract String => Maybe[[Symbol, String, String]]
def parse_locale_extension(path)
path_bits = path.split('.')
return nil if path_bits.size < 3
locale = path_bits.delete_at(-2).to_sym
return nil unless locales.include?(locale)
path = path_bits.join('.')
basename = File.basename(path_bits[0..-2].join('.'))
[locale, path, basename]
end
LocalizedPageDescriptor = Struct.new(:path, :source_path, :locale) do
def execute_descriptor(app, resources)
r = ::Middleman::Sitemap::ProxyResource.new(app.sitemap, path, source_path)
r.add_metadata options: { locale: locale }
resources + [r]
end
end
Contract String, String, String, Symbol => LocalizedPageDescriptor
def build_resource(path, source_path, page_id, locale)
old_locale = ::I18n.locale
::I18n.locale = locale
localized_page_id = ::I18n.t("paths.#{page_id}", default: page_id, fallback: false)
partially_localized_path = ''
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, fallback: false)}"
end
path = "#{partially_localized_path}/#{File.basename(path)}"
prefix = path_root(locale)
# path needs to be changed if file has a localizable extension. (options[mount_at_root] == locale)
path = ::Middleman::Util.normalize_path(
File.join(prefix, path.sub(page_id, localized_page_id))
)
path = path.sub(options[:templates_dir] + '/', '')
::I18n.locale = old_locale
LocalizedPageDescriptor.new(path, source_path, locale)
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/default_helpers.rb | middleman-core/lib/middleman-core/core_extensions/default_helpers.rb | require 'padrino-helpers'
require 'padrino-helpers/output_helpers'
require 'padrino-helpers/asset_tag_helpers'
require 'padrino-helpers/form_helpers'
require 'padrino-helpers/format_helpers'
require 'padrino-helpers/number_helpers'
require 'padrino-helpers/output_helpers'
require 'padrino-helpers/render_helpers'
require 'active_support/core_ext/array/extract_options'
require 'middleman-core/contracts'
# Don't fail on invalid locale, that's not what our current
# users expect.
::I18n.enforce_available_locales = false
class Padrino::Helpers::OutputHelpers::ErbHandler
# Force Erb capture not to use safebuffer
def capture_from_template(*args, &block)
self.output_buffer = ''
buf_was = output_buffer
raw = yield(*args)
captured = template.instance_variable_get(:@_out_buf)
self.output_buffer = buf_was
engine_matches?(block) && !captured.empty? ? captured : raw
end
end
class Middleman::CoreExtensions::DefaultHelpers < ::Middleman::Extension
define_setting :relative_links, false, 'Whether to generate relative links instead of absolute ones'
def initialize(app, options_hash={}, &block)
super
require 'active_support/core_ext/object/to_query'
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::OutputHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::TagHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::AssetTagHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::FormHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::FormatHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::RenderHelpers
::Middleman::TemplateContext.send :include, ::Padrino::Helpers::NumberHelpers
# ::Middleman::TemplateContext.send :include, ::Padrino::Helpers::TranslationHelpers
end
# The helpers
helpers do
# Make all block content html_safe
def content_tag(name, content=nil, options=nil, &block)
# safe_content_tag(name, content, options, &block)
if block_given?
options = content if content.is_a?(Hash)
content = capture_html(&block)
end
options = parse_data_options(name, options)
attributes = tag_attributes(options)
output = ActiveSupport::SafeBuffer.new
output.safe_concat "<#{name}#{attributes}>"
if content.respond_to?(:each) && !content.is_a?(String)
content.each do |c|
output.safe_concat c
output.safe_concat ::Padrino::Helpers::TagHelpers::NEWLINE
end
else
output.safe_concat content.to_s
end
output.safe_concat "</#{name}>"
block_is_template?(block) ? concat_content(output) : output
end
def capture_html(*args, &block)
result = if handler = auto_find_proper_handler(&block)
handler.capture_from_template(*args, &block)
else
yield(*args)
end
::ActiveSupport::SafeBuffer.new.safe_concat(result)
end
def auto_find_proper_handler(&block)
if block_given?
engine = File.extname(block.source_location[0])[1..-1].to_sym
::Padrino::Helpers::OutputHelpers.handlers.select { |e, _| e == engine }.values.map { |h| h.new(self) }.find { |h| h.engine_matches?(block) }
else
find_proper_handler
end
end
# Disable Padrino cache buster
def asset_stamp
false
end
# Output a stylesheet link tag based on the current path
#
# @return [String]
def auto_stylesheet_link_tag
auto_tag(:css) do |path|
stylesheet_link_tag path
end
end
# Output a javascript tag based on the current path
#
# @return [String]
def auto_javascript_include_tag
auto_tag(:js) do |path|
javascript_include_tag path
end
end
# Override helper to add `relative` opt-out.
def stylesheet_link_tag(*sources)
options = {
rel: 'stylesheet'
}.update(sources.extract_options!.symbolize_keys)
path_options = {}
path_options[:relative] = options.delete(:relative) if options.key?(:relative)
sources.flatten.reduce(::ActiveSupport::SafeBuffer.new) do |all, source|
all << tag(:link, {
href: asset_path(:css, source, path_options)
}.update(options))
end
end
# Override helper to add `relative` opt-out.
def javascript_include_tag(*sources)
options = sources.extract_options!.symbolize_keys
path_options = {}
path_options[:relative] = options.delete(:relative) if options.key?(:relative)
sources.flatten.reduce(::ActiveSupport::SafeBuffer.new) do |all, source|
all << content_tag(:script, nil, {
src: asset_path(:js, source, path_options)
}.update(options))
end
end
# Output a stylesheet link tag based on the current path
#
# @param [Symbol] asset_ext The type of asset
# @param [String] asset_dir Where to look for assets
# @return [void]
def auto_tag(asset_ext, asset_dir=nil)
if asset_dir.nil?
asset_dir = case asset_ext
when :js
config[:js_dir]
when :css
config[:css_dir]
end
end
# If the basename of the request as no extension, assume we are serving a
# directory and join index_file to the path.
path = File.join(asset_dir, current_resource.path)
path = path[0..-(File.extname(path).length + 1)] + ".#{asset_ext}"
yield path if sitemap.find_resource_by_path(path)
end
# Generate body css classes based on the current path
#
# @return [String]
def page_classes(path=current_path.dup, options={})
if path.is_a? Hash
options = path
path = current_path.dup
end
path << index_file if path.end_with?('/')
path = ::Middleman::Util.strip_leading_slash(path)
classes = Set.new
parts = path.split('.').first.split('/')
parts.each_with_index { |_, i| classes << parts.first(i + 1).join('_') }
prefix = options[:numeric_prefix] || 'x'
classes.map do |c|
# Replace weird class name characters
c = c.gsub(/[^a-zA-Z0-9\-_]/, '-')
# Class names can't start with a digit
c = "#{prefix}#{c}" if c =~ /\A\d/
c
end.join(' ')
end
# Get the path of a file of a given type
#
# @param [Symbol] kind The type of file
# @param [String] source The path to the file
# @param [Hash] options Data to pass through.
# @return [String]
def asset_path(kind, source, options={})
options_with_resource = {}.merge!(options).merge!(current_resource: current_resource)
::Middleman::Util.asset_path(app, kind, source, options_with_resource)
end
# Get the URL of an asset given a type/prefix
#
# @param [String] path The path (such as "photo.jpg")
# @param [String] prefix The type prefix (such as "images")
# @param [Hash] options Additional options.
# @return [String] The fully qualified asset url
def asset_url(path, prefix='', options={})
options_with_resource = {}.merge!(options).merge!(current_resource: current_resource)
::Middleman::Util.asset_url(app, path, prefix, options_with_resource)
end
# Given a source path (referenced either absolutely or relatively)
# or a Resource, this will produce the nice URL configured for that
# path, respecting :relative_links, directory indexes, etc.
#
# Relative routes will be relative the the current_resource. Pass the
# `:current_resource` option to customize.
def url_for(path_or_resource, options={})
options_with_resource = {}.merge!(current_resource: current_resource).merge!(options)
::Middleman::Util.url_for(app, path_or_resource, options_with_resource)
end
# Overload the regular link_to to be sitemap-aware - if you
# reference a source path, either absolutely or relatively,
# you'll get that resource's nice URL. Also, there is a
# :relative option which, if set to true, will produce
# relative URLs instead of absolute URLs. You can also add
#
# config[:relative_links] = true
#
# to config.rb to have all links default to relative.
#
# There is also a :query option that can be used to append a
# query string, which can be expressed as either a String,
# or a Hash which will be turned into URL parameters.
def link_to(*args, &block)
url_arg_index = block_given? ? 0 : 1
options_index = block_given? ? 1 : 2
if block_given? && args.size > 2
raise ArgumentError, 'Too many arguments to link_to(url, options={}, &block)'
end
if url = args[url_arg_index]
options = args[options_index] || {}
raise ArgumentError, 'Options must be a hash' unless options.is_a?(Hash)
# Transform the url through our magic url_for method
args[url_arg_index] = url_for(url, options)
# Cleanup before passing to Padrino
options.except!(:relative, :current_resource, :find_resource, :query, :anchor, :fragment)
end
super(*args, &block)
end
# Modified Padrino form_for that uses Middleman's url_for
# to transform the URL.
def form_tag(url, options={}, &block)
url = url_for(url, options)
super
end
# Modified Padrino image_tag so that it finds the paths for srcset
# using asset_path for the images listed in the srcset param
def image_tag(path, params={})
params.symbolize_keys!
if params.key?(:srcset)
images_sources = params[:srcset].split(",").map do |src_def|
if src_def.include?("//")
src_def.strip
else
image_def, size_def = src_def.strip.split(/\s+/, 2)
image_path = asset_path(:images, image_def)
if size_def
"#{image_path} #{size_def}"
else
image_path
end
end
end
params[:srcset] = images_sources.join(", ")
end
params[:alt] ||= ""
super(path, params)
end
def partial(template, options={}, &block)
including_parent_locals = {}
including_parent_locals.merge!(@locs || {})
including_parent_locals.merge!(options[:locals] || {})
options[:locals] = including_parent_locals
super(template, options, &block)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/inline_url_rewriter.rb | middleman-core/lib/middleman-core/core_extensions/inline_url_rewriter.rb | require 'rack'
require 'rack/response'
require 'memoist'
require 'middleman-core/util'
require 'middleman-core/contracts'
module Middleman
module CoreExtensions
class InlineURLRewriter < ::Middleman::Extension
include Contracts
expose_to_application rewrite_inline_urls: :add
REWRITER_DESCRIPTOR = {
id: Symbol,
proc: Or[Proc, Method],
url_extensions: ArrayOf[String],
source_extensions: ArrayOf[String],
ignore: ArrayOf[::Middleman::Util::IGNORE_DESCRIPTOR],
after: Maybe[Symbol]
}.freeze
def initialize(app, options_hash={}, &block)
super
@rewriters = {}
end
Contract REWRITER_DESCRIPTOR => Any
def add(options)
@rewriters[options] = options
end
def after_configuration
return if @rewriters.empty?
rewriters = @rewriters.values.sort do |a, b|
if b[:after] && b[:after] == a[:id]
1
else
0
end
end
app.use Rack, rewriters: rewriters, middleman_app: @app
end
class Rack
extend Memoist
include Contracts
Contract RespondTo[:call], {
middleman_app: IsA['Middleman::Application'],
rewriters: ArrayOf[REWRITER_DESCRIPTOR]
} => Any
def initialize(app, options={})
@rack_app = app
@middleman_app = options.fetch(:middleman_app)
@rewriters = options.fetch(:rewriters)
all_source_exts = @rewriters
.reduce([]) { |sum, rewriter| sum + rewriter[:source_extensions] }
.flatten
.uniq
@source_exts_regex_text = Regexp.union(all_source_exts).to_s
@all_asset_exts = @rewriters
.reduce([]) { |sum, rewriter| sum + rewriter[:url_extensions] }
.flatten
.uniq
end
def call(env)
status, headers, response = @rack_app.call(env)
# Allow configuration or upstream request to skip all rewriting
return [status, headers, response] if env['bypass_inline_url_rewriter'] == 'true'
path = ::Middleman::Util.full_path(env['PATH_INFO'], @middleman_app)
return [status, headers, response] unless path =~ /(^\/$)|(#{@source_exts_regex_text}$)/
return [status, headers, response] unless body = ::Middleman::Util.extract_response_text(response)
dirpath = ::Pathname.new(File.dirname(path))
rewritten = ::Middleman::Util.instrument 'inline_url_rewriter', path: path do
::Middleman::Util.rewrite_paths(body, path, @all_asset_exts, @middleman_app) do |asset_path|
uri = ::Middleman::Util.parse_uri(asset_path)
relative_path = uri.host.nil?
full_asset_path = if relative_path
dirpath.join(asset_path).to_s
else
asset_path
end
@rewriters.each do |rewriter|
uid = rewriter.fetch(:id)
# Allow upstream request to skip this specific rewriting
next if env["bypass_inline_url_rewriter_#{uid}"] == 'true'
exts = rewriter.fetch(:url_extensions)
next unless exts.include?(::File.extname(asset_path))
source_exts = rewriter.fetch(:source_extensions)
next unless source_exts.include?(::File.extname(path))
ignore = rewriter.fetch(:ignore)
next if ignore.any? { |r| ::Middleman::Util.should_ignore?(r, full_asset_path) }
rewrite_ignore = Array(rewriter[:rewrite_ignore] || [])
next if rewrite_ignore.any? { |i| ::Middleman::Util.path_match(i, path) }
proc = rewriter.fetch(:proc)
result = proc.call(asset_path, dirpath, path)
asset_path = result if result
end
asset_path
end
end
# Rewriting might have changed Content-Length, so we need
# to reset it to the actual result. The rewritten result is
# always a String, not an Array or Enumerable.
headers['Content-Length'] = rewritten.bytesize.to_s
::Rack::Response.new(
rewritten,
status,
headers
).finish
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/show_exceptions.rb | middleman-core/lib/middleman-core/core_extensions/show_exceptions.rb | require 'rack/show_exceptions'
# Support rack/showexceptions during development
module Middleman::CoreExtensions
class ShowExceptions < ::Middleman::Extension
define_setting :show_exceptions, ENV['TEST'] ? false : true, 'Whether to catch and display exceptions'
def ready
app.use ::Rack::ShowExceptions if !app.build? && app.config[:show_exceptions]
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/collections.rb | middleman-core/lib/middleman-core/core_extensions/collections.rb | require 'monitor'
require 'middleman-core/core_extensions/collections/pagination'
require 'middleman-core/core_extensions/collections/step_context'
require 'middleman-core/core_extensions/collections/lazy_root'
require 'middleman-core/core_extensions/collections/lazy_step'
# Super "class-y" injection of array helpers
class Array
include Middleman::Pagination::ArrayHelpers
end
module Middleman
module CoreExtensions
module Collections
class CollectionsExtension < Extension
# This should run after most other sitemap manipulators so that it
# gets a chance to modify any new resources that get added.
self.resource_list_manipulator_priority = 110
attr_accessor :leaves
# Expose `resources`, `data`, and `collection` to config.
expose_to_config resources: :sitemap_collector,
data: :data_collector,
collection: :register_collector,
live: :live_collector
# Exposes `collection` to templates
expose_to_template collection: :collector_value
helpers do
def pagination
current_resource.data.pagination
end
end
def initialize(app, options_hash={}, &block)
super
@leaves = Set.new
@collectors_by_name = {}
@values_by_name = {}
@collector_roots = []
@lock = Monitor.new
end
def before_configuration
@leaves.clear
end
Contract Symbol, LazyCollectorStep => Any
def register_collector(label, endpoint)
@collectors_by_name[label] = endpoint
end
Contract LazyCollectorRoot
def sitemap_collector
live_collector { |_, resources| resources }
end
Contract LazyCollectorRoot
def data_collector
live_collector { |app, _| app.data }
end
Contract Proc => LazyCollectorRoot
def live_collector(&block)
root = LazyCollectorRoot.new(self)
@collector_roots << {
root: root,
block: block
}
root
end
Contract Symbol => Any
def collector_value(label)
@values_by_name[label]
end
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
@lock.synchronize do
@collector_roots.each do |pair|
dataset = pair[:block].call(app, resources)
pair[:root].realize!(dataset)
end
ctx = StepContext.new(app)
StepContext.current = ctx
leaves = @leaves.dup
@collectors_by_name.each do |k, v|
@values_by_name[k] = v.value(ctx)
leaves.delete v
end
# Execute code paths
leaves.each do |v|
v.value(ctx)
end
# Inject descriptors
results = ctx.descriptors.reduce(resources) do |sum, d|
d.execute_descriptor(app, sum)
end
StepContext.current = nil
results
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/collections/lazy_root.rb | middleman-core/lib/middleman-core/core_extensions/collections/lazy_root.rb | require 'middleman-core/core_extensions/collections/lazy_step'
module Middleman
module CoreExtensions
module Collections
class LazyCollectorRoot
def initialize(parent)
@data = nil
@parent = parent
end
def realize!(data)
@data = data
end
def value(_ctx=nil)
@data
end
def leaves
@parent.leaves
end
def method_missing(name, *args, &block)
LazyCollectorStep.new(name, args, block, self)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/collections/step_context.rb | middleman-core/lib/middleman-core/core_extensions/collections/step_context.rb | module Middleman
module CoreExtensions
module Collections
class StepContext
class << self
attr_accessor :current
def add_to_context(name, &func)
send(:define_method, :"_internal_#{name}", &func)
end
end
attr_reader :descriptors
def initialize(app)
@app = app
@descriptors = []
end
def method_missing(name, *args, &block)
internal = :"_internal_#{name}"
if respond_to?(internal)
send(internal, *args, &block).tap do |r|
@descriptors << r if r.respond_to?(:execute_descriptor)
end
else
@app.config_context.send(name, *args, &block)
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/collections/pagination.rb | middleman-core/lib/middleman-core/core_extensions/collections/pagination.rb | require 'active_support/core_ext/object/deep_dup'
require 'middleman-core/util'
module Middleman
module Pagination
module ArrayHelpers
def per_page(per_page)
return to_enum(__method__, per_page) unless block_given?
parts = if per_page.respond_to? :call
per_page.call(dup)
else
each_slice(per_page).reduce([]) do |sum, items|
sum << items
end
end
num_pages = parts.length
collection = self
current_start_i = 0
parts.each_with_index do |items, i|
num = i + 1
meta = ::Middleman::Pagination.page_locals(
num,
num_pages,
collection,
items,
current_start_i
)
yield items, num, meta, num >= num_pages
current_start_i += items.length
end
end
end
def self.page_locals(page_num, num_pages, collection, items, page_start)
per_page = items.length
# Index into collection of the last item of this page
page_end = (page_start + per_page) - 1
::Middleman::Util.recursively_enhance(page_number: page_num,
num_pages: num_pages,
per_page: per_page,
# The range of item numbers on this page
# (1-based, for showing "Items X to Y of Z")
page_start: page_start + 1,
page_end: [page_end + 1, collection.length].min,
# Use "collection" in templates.
collection: collection)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/core_extensions/collections/lazy_step.rb | middleman-core/lib/middleman-core/core_extensions/collections/lazy_step.rb | module Middleman
module CoreExtensions
module Collections
class LazyCollectorStep
DELEGATE = [:hash, :eql?].freeze
def initialize(name, args, block, parent=nil)
@name = name
@args = args
@block = block
@parent = parent
@result = nil
leaves << self
end
def leaves
@parent.leaves
end
def value(ctx=nil)
data = @parent.value(ctx)
original_block = @block
if original_block
b = if ctx
::Proc.new do |*args|
ctx.instance_exec(*args, &original_block)
end
else
original_block
end
end
data.send(@name, *@args.deep_dup, &b)
end
def method_missing(name, *args, &block)
return ::Kernel.send(name, *args, &block) if DELEGATE.include? name
leaves.delete self
LazyCollectorStep.new(name, args, block, self)
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/asset_hash.rb | middleman-core/lib/middleman-core/extensions/asset_hash.rb | require 'addressable/uri'
require 'middleman-core/util'
require 'middleman-core/rack'
class Middleman::Extensions::AssetHash < ::Middleman::Extension
option :sources, %w(.css .htm .html .js .php .xhtml), 'List of extensions that are searched for hashable assets.'
option :exts, nil, 'List of extensions that get asset hashes appended to them.'
option :ignore, [], 'Regexes of filenames to skip adding asset hashes to'
option :rewrite_ignore, [], 'Regexes of filenames to skip processing for path rewrites'
option :prefix, '', 'Prefix for hash'
option :rename_proc, proc { |path, basename, digest, extension, options|
"#{path}#{basename}-#{options.prefix}#{digest}#{extension}"
}, 'Accepts path parameters and returns path name'
def initialize(app, options_hash={}, &block)
super
require 'addressable/uri'
require 'digest/sha1'
require 'rack/mock'
# Allow specifying regexes to ignore, plus always ignore apple touch icons
@ignore = Array(options.ignore) + [/^apple-touch-icon/]
# Exclude .ico from the default list because browsers expect it
# to be named "favicon.ico"
@exts = options.exts || (app.config[:asset_extensions] - %w(.ico))
app.rewrite_inline_urls id: :asset_hash,
url_extensions: @exts.sort.reverse,
source_extensions: options.sources,
ignore: @ignore,
rewrite_ignore: options.rewrite_ignore,
proc: method(:rewrite_url),
after: :asset_host
end
Contract String, Or[String, Pathname], Any => Maybe[String]
def rewrite_url(asset_path, dirpath, _request_path)
uri = ::Middleman::Util.parse_uri(asset_path)
relative_path = !uri.path.start_with?('/')
full_asset_path = if relative_path
dirpath.join(asset_path).to_s
else
asset_path
end
return unless asset_page = app.sitemap.find_resource_by_destination_path(full_asset_path) || app.sitemap.find_resource_by_path(full_asset_path)
replacement_path = "/#{asset_page.destination_path}"
replacement_path = Pathname.new(replacement_path).relative_path_from(dirpath).to_s if relative_path
replacement_path
end
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
@rack_client ||= begin
rack_app = ::Middleman::Rack.new(app).to_app
::Rack::MockRequest.new(rack_app)
end
# Process resources in order: binary images and fonts, then SVG, then JS/CSS.
# This is so by the time we get around to the text files (which may reference
# images and fonts) the static assets' hashes are already calculated.
resources.sort_by do |a|
if %w(.svg .svgz).include? a.ext
0
elsif %w(.js .css).include? a.ext
1
else
-1
end
end.each(&method(:manipulate_single_resource))
end
Contract IsA['Middleman::Sitemap::Resource'] => Maybe[IsA['Middleman::Sitemap::Resource']]
def manipulate_single_resource(resource)
return unless @exts.include?(resource.ext)
return if ignored_resource?(resource)
return if resource.ignored?
digest = if resource.binary?
::Digest::SHA1.file(resource.source_file).hexdigest[0..7]
else
# Render through the Rack interface so middleware and mounted apps get a shot
response = @rack_client.get(
Addressable::URI.encode(resource.destination_path),
'bypass_inline_url_rewriter_asset_hash' => 'true'
)
raise "#{resource.path} should be in the sitemap!" unless response.status == 200
::Digest::SHA1.hexdigest(response.body)[0..7]
end
path, basename, extension = split_path(resource.destination_path)
resource.destination_path = options.rename_proc.call(path, basename, digest, extension, options)
resource
end
Contract IsA['Middleman::Sitemap::Resource'] => Bool
def ignored_resource?(resource)
@ignore.any? do |ignore|
Middleman::Util.path_match(ignore, resource.destination_path)
end
end
private
# Splits resource path into path, basename and extension
# (e.g. "/images/landscape.png" => ["/images/", "landscape", ".png]
def split_path(filepath)
basename = File.basename(filepath, extension = File.extname(filepath))
path = filepath.chomp(basename + extension)
[path, basename, extension]
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/minify_css.rb | middleman-core/lib/middleman-core/extensions/minify_css.rb | require 'active_support/core_ext/object/try'
require 'memoist'
require 'middleman-core/contracts'
require 'sassc'
# Minify CSS Extension
class Middleman::Extensions::MinifyCss < ::Middleman::Extension
option :inline, false, 'Whether to minify CSS inline within HTML files'
option :ignore, [], 'Patterns to avoid minifying'
option :compressor, proc {
SassCompressor
}, 'Set the CSS compressor to use.'
option :content_types, %w(text/css), 'Content types of resources that contain CSS'
option :inline_content_types, %w(text/html text/php), 'Content types of resources that contain inline CSS'
def ready
# Setup Rack middleware to minify CSS
app.use Rack, compressor: options[:compressor],
ignore: Array(options[:ignore]) + [/\.min\./],
inline: options[:inline],
content_types: options[:content_types],
inline_content_types: options[:inline_content_types]
end
class SassCompressor
COMPRESSED_OPTIONS = { style: :compressed }.freeze
def self.compress(style, options={})
options = options.merge(COMPRESSED_OPTIONS)
::SassC::Engine.new(style, options).render.strip
end
end
# Rack middleware to look for CSS and compress it
class Rack
extend Memoist
include Contracts
INLINE_CSS_REGEX = /(<style[^>]*>\s*(?:\/\*<!\[CDATA\[\*\/\n)?)(.*?)((?:(?:\n\s*)?\/\*\]\]>\*\/)?\s*<\/style>)/m
# Init
# @param [Class] app
# @param [Hash] options
Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER],
inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
} => Any
def initialize(app, options={})
@app = app
@ignore = options.fetch(:ignore)
@inline = options.fetch(:inline)
@compressor = options.fetch(:compressor)
@compressor = @compressor.to_proc if @compressor.respond_to? :to_proc
@compressor = @compressor.call if @compressor.is_a? Proc
@content_types = options[:content_types]
@inline_content_types = options[:inline_content_types]
end
# Rack interface
# @param [Rack::Environmemt] env
# @return [Array]
def call(env)
status, headers, response = @app.call(env)
content_type = headers['Content-Type'].try(:slice, /^[^;]*/)
path = env['PATH_INFO']
minified = if @inline && minifiable_inline?(content_type)
minify_inline(::Middleman::Util.extract_response_text(response))
elsif minifiable?(content_type) && !ignore?(path)
minify(::Middleman::Util.extract_response_text(response))
end
if minified
headers['Content-Length'] = minified.bytesize.to_s
response = [minified]
end
[status, headers, response]
end
private
# Whether the path should be ignored
# @param [String] path
# @return [Boolean]
def ignore?(path)
@ignore.any? { |ignore| ::Middleman::Util.path_match(ignore, path) }
end
memoize :ignore?
# Whether this type of content can be minified
# @param [String, nil] content_type
# @return [Boolean]
def minifiable?(content_type)
@content_types.include?(content_type)
end
memoize :minifiable?
# Whether this type of content contains inline content that can be minified
# @param [String, nil] content_type
# @return [Boolean]
def minifiable_inline?(content_type)
@inline_content_types.include?(content_type)
end
memoize :minifiable_inline?
# Minify the content
# @param [String] content
# @return [String]
def minify(content)
@compressor.compress(content)
end
memoize :minify
# Detect and minify inline content
# @param [String] content
# @return [String]
def minify_inline(content)
content.gsub(INLINE_CSS_REGEX) do
$1 + minify($2) + $3
end
end
memoize :minify_inline
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/minify_javascript.rb | middleman-core/lib/middleman-core/extensions/minify_javascript.rb | require 'active_support/core_ext/object/try'
require 'middleman-core/contracts'
require 'memoist'
# Minify Javascript Extension
class Middleman::Extensions::MinifyJavascript < ::Middleman::Extension
option :inline, false, 'Whether to minify JS inline within HTML files'
option :ignore, [], 'Patterns to avoid minifying'
option :compressor, proc {
require 'uglifier'
::Uglifier.new
}, 'Set the JS compressor to use.'
option :content_types, %w(text/javascript), 'Content types of resources that contain JS'
option :inline_content_types, %w(text/html text/php), 'Content types of resources that contain inline JS'
def ready
# Setup Rack middleware to minify JS
app.use Rack, compressor: options[:compressor],
ignore: Array(options[:ignore]) + [/\.min\./],
inline: options[:inline],
content_types: options[:content_types],
inline_content_types: options[:inline_content_types]
end
# Rack middleware to look for JS and compress it
class Rack
extend Memoist
include Contracts
INLINE_JS_REGEX = /(<script[^>]*>\s*(?:\/\/(?:(?:<!--)|(?:<!\[CDATA\[))\n)?)(.*?)((?:(?:\n\s*)?\/\/(?:(?:-->)|(?:\]\]>)))?\s*<\/script>)/m
# Init
# @param [Class] app
# @param [Hash] options
Contract RespondTo[:call], {
ignore: ArrayOf[PATH_MATCHER],
inline: Bool,
compressor: Or[Proc, RespondTo[:to_proc], RespondTo[:compress]]
} => Any
def initialize(app, options={})
@app = app
@ignore = options.fetch(:ignore)
@inline = options.fetch(:inline)
@compressor = options.fetch(:compressor)
@compressor = @compressor.to_proc if @compressor.respond_to? :to_proc
@compressor = @compressor.call if @compressor.is_a? Proc
@content_types = options[:content_types]
@inline_content_types = options[:inline_content_types]
end
# Rack interface
# @param [Rack::Environmemt] env
# @return [Array]
def call(env)
status, headers, response = @app.call(env)
type = headers['Content-Type'].try(:slice, /^[^;]*/)
@path = env['PATH_INFO']
minified = if @inline && minifiable_inline?(type)
minify_inline(::Middleman::Util.extract_response_text(response))
elsif minifiable?(type) && !ignore?(@path)
minify(::Middleman::Util.extract_response_text(response))
end
if minified
headers['Content-Length'] = minified.bytesize.to_s
response = [minified]
end
[status, headers, response]
end
private
# Whether the path should be ignored
# @param [String] path
# @return [Boolean]
def ignore?(path)
@ignore.any? { |ignore| Middleman::Util.path_match(ignore, path) }
end
memoize :ignore?
# Whether this type of content can be minified
# @param [String, nil] content_type
# @return [Boolean]
def minifiable?(content_type)
@content_types.include?(content_type)
end
memoize :minifiable?
# Whether this type of content contains inline content that can be minified
# @param [String, nil] content_type
# @return [Boolean]
def minifiable_inline?(content_type)
@inline_content_types.include?(content_type)
end
memoize :minifiable_inline?
# Minify the content
# @param [String] content
# @return [String]
def minify(content)
@compressor.compress(content)
rescue ExecJS::ProgramError => e
warn "WARNING: Couldn't compress JavaScript in #{@path}: #{e.message}"
content
end
memoize :minify
# Detect and minify inline content
# @param [String] content
# @return [String]
def minify_inline(content)
content.gsub(INLINE_JS_REGEX) do |match|
first = $1
inline_content = $2
last = $3
# Only compress script tags that contain JavaScript (as opposed to
# something like jQuery templates, identified with a "text/html" type).
if !first.include?('type=') || first.include?('text/javascript')
first + minify(inline_content) + last
else
match
end
end
end
memoize :minify_inline
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/asset_host.rb | middleman-core/lib/middleman-core/extensions/asset_host.rb | require 'addressable/uri'
class Middleman::Extensions::AssetHost < ::Middleman::Extension
option :host, nil, 'The asset host to use or a Proc to determine asset host', required: true
option :exts, nil, 'List of extensions that get cache busters strings appended to them.'
option :sources, %w(.css .htm .html .js .php .xhtml), 'List of extensions that are searched for bustable assets.'
option :ignore, [], 'Regexes of filenames to skip adding query strings to'
option :rewrite_ignore, [], 'Regexes of filenames to skip processing for host rewrites'
def initialize(app, options_hash={}, &block)
super
app.rewrite_inline_urls id: :asset_host,
url_extensions: options.exts || app.config[:asset_extensions],
source_extensions: options.sources,
ignore: options.ignore,
rewrite_ignore: options.rewrite_ignore,
proc: method(:rewrite_url)
end
Contract String, Or[String, Pathname], Any => String
def rewrite_url(asset_path, dirpath, _request_path)
uri = ::Middleman::Util.parse_uri(asset_path)
relative_path = uri.path[0..0] != '/'
full_asset_path = if relative_path
dirpath.join(asset_path).to_s
else
asset_path
end
asset_prefix = if options[:host].is_a?(Proc)
options[:host].call(full_asset_path)
elsif options[:host].is_a?(String)
options[:host]
end
File.join(asset_prefix, full_asset_path)
end
memoize :rewrite_url
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/cache_buster.rb | middleman-core/lib/middleman-core/extensions/cache_buster.rb | # The Cache Buster extension
class Middleman::Extensions::CacheBuster < ::Middleman::Extension
option :exts, nil, 'List of extensions that get cache busters strings appended to them.'
option :sources, %w(.css .htm .html .js .php .xhtml), 'List of extensions that are searched for bustable assets.'
option :ignore, [], 'Regexes of filenames to skip adding query strings to'
option :rewrite_ignore, [], 'Regexes of filenames to skip processing for path rewrites'
def initialize(app, options_hash={}, &block)
super
app.rewrite_inline_urls id: :cache_buster,
url_extensions: options.exts || app.config[:asset_extensions],
source_extensions: options.sources,
ignore: options.ignore,
rewrite_ignore: options.rewrite_ignore,
proc: method(:rewrite_url)
end
Contract String, Or[String, Pathname], Any => String
def rewrite_url(asset_path, _dirpath, _request_path)
asset_path + '?' + Time.now.strftime('%s')
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/automatic_alt_tags.rb | middleman-core/lib/middleman-core/extensions/automatic_alt_tags.rb | # Automatic Image alt tags from image names extension
class Middleman::Extensions::AutomaticAltTags < ::Middleman::Extension
helpers do
# Override default image_tag helper to automatically insert alt tag
# containing image name.
def image_tag(path, params={})
unless path.include?('://')
params[:alt] ||= ''
real_path = path.dup
real_path = File.join(config[:images_dir], real_path) unless real_path.start_with?('/')
file = app.files.find(:source, real_path)
if file && file[:full_path].exist?
begin
alt_text = File.basename(file[:full_path].to_s, '.*')
alt_text.capitalize!
params[:alt] = alt_text
end
end
end
super(path, params)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/relative_assets.rb | middleman-core/lib/middleman-core/extensions/relative_assets.rb | require 'addressable/uri'
# Relative Assets extension
class Middleman::Extensions::RelativeAssets < ::Middleman::Extension
option :exts, nil, 'List of extensions that get converted to relative paths.'
option :sources, %w(.css .htm .html .xhtml), 'List of extensions that are searched for relative assets.'
option :ignore, [], 'Regexes of filenames to skip converting to relative paths.'
option :rewrite_ignore, [], 'Regexes of filenames to skip processing for path rewrites.'
option :helpers_only, false, 'Allow only Ruby helpers to change paths.'
def initialize(app, options_hash={}, &block)
super
return if options[:helpers_only]
app.rewrite_inline_urls id: :relative_assets,
url_extensions: options.exts || app.config[:asset_extensions],
source_extensions: options.sources,
ignore: options.ignore,
rewrite_ignore: options.rewrite_ignore,
proc: method(:rewrite_url)
end
def mark_as_relative(file_path, opts, current_resource)
result = opts.dup
valid_exts = options.sources
return result unless current_resource
return result unless valid_exts.include?(current_resource.ext)
rewrite_ignores = Array(options.rewrite_ignore || [])
path = current_resource.destination_path
return result if rewrite_ignores.any? do |i|
::Middleman::Util.path_match(i, path) || ::Middleman::Util.path_match(i, "/#{path}")
end
return result if Array(options.ignore || []).any? do |r|
::Middleman::Util.should_ignore?(r, file_path)
end
result[:relative] = true unless result.key?(:relative)
result
end
helpers do
def asset_url(path, prefix='', options={})
super(path, prefix, app.extensions[:relative_assets].mark_as_relative(super, options, current_resource))
end
def asset_path(kind, source, options={})
super(kind, source, app.extensions[:relative_assets].mark_as_relative(super, options, current_resource))
end
end
Contract String, Or[String, Pathname], Any => Maybe[String]
def rewrite_url(asset_path, dirpath, request_path)
uri = ::Middleman::Util.parse_uri(asset_path)
return if uri.path[0..0] != '/'
relative_path = uri.host.nil?
full_asset_path = if relative_path
dirpath.join(asset_path).to_s
else
asset_path
end
current_dir = Pathname(request_path).dirname
result = Pathname(full_asset_path).relative_path_from(current_dir).to_s
result
end
memoize :rewrite_url
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/automatic_image_sizes.rb | middleman-core/lib/middleman-core/extensions/automatic_image_sizes.rb | # Automatic Image Sizes extension
class Middleman::Extensions::AutomaticImageSizes < ::Middleman::Extension
def initialize(app, options_hash={}, &block)
super
# Include 3rd-party fastimage library
require 'fastimage'
end
helpers do
# Override default image_tag helper to automatically calculate and include
# image dimensions.
#
# @param [String] path
# @param [Hash] params
# @return [String]
def image_tag(path, params={})
if !params.key?(:width) && !params.key?(:height) && !path.include?('://')
real_path = path.dup
real_path = File.join(config[:images_dir], real_path) unless real_path.start_with?('/')
file = app.files.find(:source, real_path) || app.files.find(:source, real_path.sub(/^\//, ''))
if file && file[:full_path].exist?
begin
full_path = file[:full_path].to_s
width, height = ::FastImage.size(full_path, raise_on_failure: true)
# Check for @2x and @3x image
retina = full_path.match(/@(\d)x\.[a-zA-Z]{3,4}$/)
if retina
factor = retina[1].to_i
width /= factor
height /= factor
end
params[:width] = width
params[:height] = height
rescue FastImage::UnknownImageType
# No message, it's just not supported
rescue
warn "Couldn't determine dimensions for image #{path}: #{$ERROR_INFO.message}"
end
end
end
super(path, params)
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/gzip.rb | middleman-core/lib/middleman-core/extensions/gzip.rb | # This extension Gzips assets and pages when building.
# Gzipped assets and pages can be served directly by Apache or
# Nginx with the proper configuration, and pre-zipping means that we
# can use a more agressive compression level at no CPU cost per request.
#
# Use Nginx's gzip_static directive, or AddEncoding and mod_rewrite in Apache
# to serve your Gzipped files whenever the normal (non-.gz) filename is requested.
#
# Pass the :exts options to customize which file extensions get zipped (defaults
# to .css, .htm, .html, .js, and .xhtml
#
class Middleman::Extensions::Gzip < ::Middleman::Extension
option :exts, %w(.css .htm .html .js .svg .xhtml), 'File extensions to Gzip when building.'
option :ignore, [], 'Patterns to avoid gzipping'
option :overwrite, false, 'Overwrite original files instead of adding .gz extension.'
class NumberHelpers
include ::Padrino::Helpers::NumberHelpers
end
def initialize(app, options_hash={})
super
require 'zlib'
require 'stringio'
require 'find'
require 'thread'
end
def after_build(builder)
num_threads = 4
paths = ::Middleman::Util.all_files_under(app.config[:build_dir])
total_savings = 0
# Fill a queue with inputs
in_queue = Queue.new
paths.each do |path|
in_queue << path if should_gzip?(path)
end
num_paths = in_queue.size
# Farm out gzip tasks to threads and put the results in in_queue
out_queue = Queue.new
num_threads.times.each do
Thread.new do
while path = in_queue.pop
out_queue << gzip_file(path.to_s)
end
end
end
# Insert a nil for each thread to stop it
num_threads.times do
in_queue << nil
end
old_locale = I18n.locale
I18n.locale = :en # use the english localizations for printing out file sizes to make sure the localizations exist
num_paths.times do
output_filename, old_size, new_size = out_queue.pop
next unless output_filename
total_savings += (old_size - new_size)
size_change_word = (old_size - new_size) > 0 ? 'smaller' : 'larger'
builder.trigger :created, "#{output_filename} (#{NumberHelpers.new.number_to_human_size((old_size - new_size).abs)} #{size_change_word})"
end
builder.trigger :gzip, '', "Total gzip savings: #{NumberHelpers.new.number_to_human_size(total_savings)}"
I18n.locale = old_locale
end
Contract String => [Maybe[String], Maybe[Num], Maybe[Num]]
def gzip_file(path)
input_file = File.open(path, 'rb').read
output_filename = options.overwrite ? path : path + '.gz'
input_file_time = File.mtime(path)
# Check if the right file's already there
if !options.overwrite && File.exist?(output_filename) && File.mtime(output_filename) == input_file_time
return [nil, nil, nil]
end
File.open(output_filename, 'wb') do |f|
gz = Zlib::GzipWriter.new(f, Zlib::BEST_COMPRESSION)
gz.mtime = input_file_time.to_i
gz.write input_file
gz.close
end
# Make the file times match, both for Nginx's gzip_static extension
# and so we can ID existing files. Also, so even if the GZ files are
# wiped out by build --clean and recreated, we won't rsync them over
# again because they'll end up with the same mtime.
File.utime(File.atime(output_filename), input_file_time, output_filename)
old_size = File.size(path)
new_size = File.size(output_filename)
[output_filename, old_size, new_size]
end
private
# Whether a path should be gzipped
# @param [Pathname] path A destination path
# @return [Boolean]
Contract Pathname => Bool
def should_gzip?(path)
path = path.sub app.config[:build_dir] + '/', ''
options.exts.include?(path.extname) && options.ignore.none? { |ignore| Middleman::Util.path_match(ignore, path.to_s) }
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/directory_indexes.rb | middleman-core/lib/middleman-core/extensions/directory_indexes.rb | # Directory Indexes extension
class Middleman::Extensions::DirectoryIndexes < ::Middleman::Extension
# This should run after most other sitemap manipulators so that it
# gets a chance to modify any new resources that get added.
self.resource_list_manipulator_priority = 100
# Update the main sitemap resource list
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
index_file = app.config[:index_file]
new_index_path = "/#{index_file}"
extensions = %w(.htm .html .php .xhtml)
resources.each do |resource|
# Check if it would be pointless to reroute
next if resource.destination_path == index_file ||
resource.destination_path.end_with?(new_index_path) ||
!extensions.include?(resource.ext)
# Check if file metadata (options set by "page" in config.rb or frontmatter) turns directory_index off
next if resource.options[:directory_index] == false
extensions.each do |ext|
resource.destination_path = resource.destination_path.chomp(ext)
end
resource.destination_path += new_index_path
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/external_pipeline.rb | middleman-core/lib/middleman-core/extensions/external_pipeline.rb | class Middleman::Extensions::ExternalPipeline < ::Middleman::Extension
self.supports_multiple_instances = true
option :name, nil, 'The name of the pipeline', required: true
option :command, nil, 'The command to initialize', required: true
option :source, nil, 'Path to merge into sitemap', required: true
option :latency, 0.25, 'Latency between refreshes of source'
option :disable_background_execution, false, "Don't run the command in a separate background thread"
option :ignore_exit_code, false, 'Ignore exit code for restart or stop of a command'
def initialize(app, config={}, &block)
super
return if app.mode?(:config)
require 'servolux'
require 'thread'
require 'fileutils'
source_path = File.expand_path(options[:source], app.root)
# Make sure it exists, or `listen` will explode.
::FileUtils.mkdir_p(source_path)
@watcher = app.files.watch :source,
path: source_path,
latency: options[:latency],
frontmatter: false
@current_thread = nil
app.reload(&method(:reload!))
logger.info "== Executing: `#{options[:command]}`"
if app.build? || options[:disable_background_execution]
watch_command!(false)
@watcher.poll_once!
else
watch_command!(true)
end
end
def reload!
if @current_thread
logger.info "== Stopping: `#{options[:command]}`"
@current_thread.stop
@current_thread = nil
end
end
def watch_command!(async)
@current_thread = ::Servolux::Child.new(
command: options[:command],
suspend: 2
)
@current_thread.start
watch_thread = Thread.new do
while buf = @current_thread.io.gets
without_newline = buf.sub(/\n$/, '')
logger.info "== External: #{without_newline}" unless without_newline.empty?
end
@current_thread.wait
if !options[:ignore_exit_code] && !@current_thread.exitstatus.nil? && @current_thread.exitstatus != 0
logger.error '== External: Command failed with non-zero exit status'
exit(1)
end
end
watch_thread.join unless async
rescue ::Errno::ENOENT => e
logger.error "== External: Command failed with message: #{e.message}"
exit(1)
end
private
def print_command(stdout)
while buf = stdout.gets
without_newline = buf.sub(/\n$/, '')
logger.info "== External: #{without_newline}" unless without_newline.empty?
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/extensions/lorem.rb | middleman-core/lib/middleman-core/extensions/lorem.rb | class Middleman::Extensions::Lorem < ::Middleman::Extension
helpers do
# Access to the Lorem object
# @return [Middleman::Extensions::Lorem::LoremObject]
def lorem
LoremObject
end
# Return a placeholder image using placekitten.com
#
# @param [String] size
# @param [Hash] options
# @return [String]
def placekitten(size, options={})
options[:domain] = 'http://placekitten.com'
lorem.image(size, options)
end
end
# Adapted from Frank:
# https://github.com/blahed/frank/
# Copyright (c) 2010 Travis Dunn
#
# Permission is hereby granted, free of charge, to any person
# obtaining a copy of this software and associated documentation
# files (the "Software"), to deal in the Software without
# restriction, including without limitation the rights to use,
# copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the
# Software is furnished to do so, subject to the following
# conditions:
#
# The above copyright notice and this permission notice shall be
# included in all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
# EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
# OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
# NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
# HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
# WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
# FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
# OTHER DEALINGS IN THE SOFTWARE.
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).freeze
# Get one placeholder word
# @return [String]
def word
words(1)
end
# Get some number of placeholder words
# @param [Fixnum] total
# @return [String]
def words(total)
(1..total).map do
randm(WORDS)
end.join(' ')
end
# Get one placeholder sentence
# @return [String]
def sentence
sentences(1)
end
# Get some number of placeholder sentences
# @param [Fixnum] total
# @return [String]
def sentences(total)
(1..total).map do
words(randm(4..15)).capitalize
end.join('. ')
end
# Get one placeholder paragraph
# @return [String]
def paragraph
paragraphs(1)
end
# Get some number of placeholder paragraphs
# @param [Fixnum] total
# @return [String]
def paragraphs(total)
(1..total).map do
sentences(randm(3..7)).capitalize
end.join("\n\n")
end
# Get a placeholder date
# @param [String] fmt
# @return [String]
def date(fmt='%a %b %d, %Y')
y = rand(20) + 1990
m = rand(12) + 1
d = rand(31) + 1
Time.local(y, m, d).strftime(fmt)
end
# Get a placeholder name
# @return [String]
def name
"#{first_name} #{last_name}"
end
# Get a placeholder first name
# @return [String]
def first_name
names = 'Judith Angelo Margarita Kerry Elaine Lorenzo Justice Doris Raul Liliana Kerry Elise Ciaran Johnny Moses Davion Penny Mohammed Harvey Sheryl Hudson Brendan Brooklynn Denis Sadie Trisha Jacquelyn Virgil Cindy Alexa Marianne Giselle Casey Alondra Angela Katherine Skyler Kyleigh Carly Abel Adrianna Luis Dominick Eoin Noel Ciara Roberto Skylar Brock Earl Dwayne Jackie Hamish Sienna Nolan Daren Jean Shirley Connor Geraldine Niall Kristi Monty Yvonne Tammie Zachariah Fatima Ruby Nadia Anahi Calum Peggy Alfredo Marybeth Bonnie Gordon Cara John Staci Samuel Carmen Rylee Yehudi Colm Beth Dulce Darius inley Javon Jason Perla Wayne Laila Kaleigh Maggie Don Quinn Collin Aniya Zoe Isabel Clint Leland Esmeralda Emma Madeline Byron Courtney Vanessa Terry Antoinette George Constance Preston Rolando Caleb Kenneth Lynette Carley Francesca Johnnie Jordyn Arturo Camila Skye Guy Ana Kaylin Nia Colton Bart Brendon Alvin Daryl Dirk Mya Pete Joann Uriel Alonzo Agnes Chris Alyson Paola Dora Elias Allen Jackie Eric Bonita Kelvin Emiliano Ashton Kyra Kailey Sonja Alberto Ty Summer Brayden Lori Kelly Tomas Joey Billie Katie Stephanie Danielle Alexis Jamal Kieran Lucinda Eliza Allyson Melinda Alma Piper Deana Harriet Bryce Eli Jadyn Rogelio Orlaith Janet Randal Toby Carla Lorie Caitlyn Annika Isabelle inn Ewan Maisie Michelle Grady Ida Reid Emely Tricia Beau Reese Vance Dalton Lexi Rafael Makenzie Mitzi Clinton Xena Angelina Kendrick Leslie Teddy Jerald Noelle Neil Marsha Gayle Omar Abigail Alexandra Phil Andre Billy Brenden Bianca Jared Gretchen Patrick Antonio Josephine Kyla Manuel Freya Kellie Tonia Jamie Sydney Andres Ruben Harrison Hector Clyde Wendell Kaden Ian Tracy Cathleen Shawn'.split(' ')
names[rand(names.size)]
end
# Get a placeholder last name
# @return [String]
def last_name
names = "Chung Chen Melton Hill Puckett Song Hamilton Bender Wagner McLaughlin McNamara Raynor Moon Woodard Desai Wallace Lawrence Griffin Dougherty Powers May Steele Teague Vick Gallagher Solomon Walsh Monroe Connolly Hawkins Middleton Goldstein Watts Johnston Weeks Wilkerson Barton Walton Hall Ross Chung Bender Woods Mangum Joseph Rosenthal Bowden Barton Underwood Jones Baker Merritt Cross Cooper Holmes Sharpe Morgan Hoyle Allen Rich Rich Grant Proctor Diaz Graham Watkins Hinton Marsh Hewitt Branch Walton O'Brien Case Watts Christensen Parks Hardin Lucas Eason Davidson Whitehead Rose Sparks Moore Pearson Rodgers Graves Scarborough Sutton Sinclair Bowman Olsen Love McLean Christian Lamb James Chandler Stout Cowan Golden Bowling Beasley Clapp Abrams Tilley Morse Boykin Sumner Cassidy Davidson Heath Blanchard McAllister McKenzie Byrne Schroeder Griffin Gross Perkins Robertson Palmer Brady Rowe Zhang Hodge Li Bowling Justice Glass Willis Hester Floyd Graves Fischer Norman Chan Hunt Byrd Lane Kaplan Heller May Jennings Hanna Locklear Holloway Jones Glover Vick O'Donnell Goldman McKenna Starr Stone McClure Watson Monroe Abbott Singer Hall Farrell Lucas Norman Atkins Monroe Robertson Sykes Reid Chandler Finch Hobbs Adkins Kinney Whitaker Alexander Conner Waters Becker Rollins Love Adkins Black Fox Hatcher Wu Lloyd Joyce Welch Matthews Chappell MacDonald Kane Butler Pickett Bowman Barton Kennedy Branch Thornton McNeill Weinstein Middleton Moss Lucas Rich Carlton Brady Schultz Nichols Harvey Stevenson Houston Dunn West O'Brien Barr Snyder Cain Heath Boswell Olsen Pittman Weiner Petersen Davis Coleman Terrell Norman Burch Weiner Parrott Henry Gray Chang McLean Eason Weeks Siegel Puckett Heath Hoyle Garrett Neal Baker Goldman Shaffer Choi Carver".split(' ')
names[rand(names.size)]
end
# Get a placeholder 140 character tweet about Philip the Purple Otter
# Via http://www.kevadamson.com/talking-of-design/article/140-alternative-characters-to-lorem-ipsum
# @return [String]
def tweet
tweets = ['Far away, in a forest next to a river beneath the mountains, there lived a small purple otter called Philip. Philip likes sausages. The End.',
'He liked the quality sausages from Marks & Spencer but due to the recession he had been forced to shop in a less desirable supermarket. End.',
'He awoke one day to find his pile of sausages missing. Roger the greedy boar with human eyes, had skateboarded into the forest & eaten them!']
tweets[rand(tweets.size)]
end
# Get a placeholder email address
# @return [String]
def email
delimiters = ['_', '-', '']
domains = %w(gmail.com yahoo.com hotmail.com email.com live.com me.com mac.com aol.com fastmail.com mail.com)
username = name.gsub(/[^\w]/, delimiters[rand(delimiters.size)])
"#{username}@#{domains[rand(domains.size)]}".downcase
end
# Get a placeholder image, using placehold.it by default
# @param [String] size
# @param [Hash] options
# @return [String]
def image(size, options={})
domain = options[:domain] || 'http://placehold.it'
src = "#{domain}/#{size}"
hex = %w(a b c d e f 0 1 2 3 4 5 6 7 8 9)
background_color = options[:background_color]
color = options[:color]
if options[:random_color]
background_color = hex.sample(6).join
color = hex.sample(6).join
end
src << "/#{background_color.sub(/^#/, '')}" if background_color
src << '/ccc' if background_color.nil? && color
src << "/#{color.sub(/^#/, '')}" if color
src << "&text=#{Rack::Utils.escape(options[:text])}" if options[:text]
src
end
# Pick a random item from a given range
# @param [Range] range
# @return [Object]
def randm(range)
a = range.to_a
a[rand(a.length)]
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/sass.rb | middleman-core/lib/middleman-core/renderers/sass.rb | require 'sassc'
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'
define_setting :sass_assets_paths, [], 'Paths to extra SASS/SCSS files'
define_setting :sass_source_maps, nil, 'Whether to inline sourcemap into Sass'
# Setup extension
def initialize(app, options={}, &block)
super
app.files.ignore :sass_cache, :source, /(^|\/)\.sass-cache\//
# Tell Tilt to use it as well (for inline sass blocks)
::Tilt.register 'sass', SassPlusCSSFilenameTemplate
::Tilt.prefer(SassPlusCSSFilenameTemplate)
# Tell Tilt to use it as well (for inline scss blocks)
::Tilt.register 'scss', ScssPlusCSSFilenameTemplate
::Tilt.prefer(ScssPlusCSSFilenameTemplate)
require 'middleman-core/renderers/sass_functions'
end
# A SassTemplate for Tilt which outputs debug messages
class SassPlusCSSFilenameTemplate < ::Tilt::SassTemplate
# Define the expected syntax for the template
# @return [Symbol]
def syntax
:sass
end
private
# Add exception messaging
# @param [Class] context
# @return [String]
def _prepare_output
@context = @options[:context]
@engine = ::SassC::Engine.new(data, sass_options)
begin
@engine.render
rescue ::SassC::SyntaxError => e
raise e if @context.app.build?
exception_to_css(e)
end
end
def exception_to_css(e)
header = "#{e.class}: #{e.message}"
<<~END
/*
#{header.gsub('*/', '*\\/')}
Backtrace:\n#{e.backtrace.join("\n").gsub('*/', '*\\/')}
*/
body:before {
white-space: pre;
font-family: monospace;
content: "#{header.gsub('"', '\"').gsub("\n", '\\A ')}"; }
END
end
# Change Sass path, for url functions, to the build folder if we're building
# @return [Hash]
def sass_options
ctx = @context
preexisting_load_paths = begin
::Sass.load_paths
rescue
[]
end
more_opts = {
load_paths: preexisting_load_paths + ctx.app.config[:sass_assets_paths],
filename: eval_file,
line: line,
syntax: syntax,
custom: {}.merge!(options[:custom] || {}).merge!(
middleman_context: ctx.app,
current_resource: ctx.current_resource
)
}
if ctx.app.config[:sass_source_maps] || (ctx.app.config[:sass_source_maps].nil? && ctx.app.development?)
more_opts[:source_map_file] = '.'
more_opts[:source_map_embed] = true
more_opts[:source_map_contents] = true
end
if ctx.is_a?(::Middleman::TemplateContext) && file
more_opts[:css_filename] = file.sub(/\.s[ac]ss$/, '')
end
{}.merge!(options).merge!(more_opts)
end
end
# SCSS version of the above template
class ScssPlusCSSFilenameTemplate < SassPlusCSSFilenameTemplate
# Define the expected syntax for the template
# @return [Symbol]
def syntax
:scss
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/kramdown.rb | middleman-core/lib/middleman-core/renderers/kramdown.rb | require 'kramdown'
module Middleman
module Renderers
# Our own Kramdown Tilt template that simply uses our custom renderer.
class KramdownTemplate < ::Tilt::KramdownTemplate
private
def _prepare_output
@context = @options[:context]
MiddlemanKramdownHTML.scope = @context
@engine = Kramdown::Document.new(data, options)
output, warnings = MiddlemanKramdownHTML.convert(@engine.root, @engine.options)
@engine.warnings.concat(warnings)
output
end
end
# Custom Kramdown renderer that uses our helpers for images and links
class MiddlemanKramdownHTML < ::Kramdown::Converter::Html
cattr_accessor :scope
def convert_img(el, _)
attrs = el.attr.dup
link = attrs.delete('src')
scope.image_tag(link, attrs)
end
def convert_a(el, indent)
content = inner(el, indent)
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
return %(<a href="#{href}">#{content}</a>)
end
attr = el.attr.dup
link = attr.delete('href')
# options to link_to are expected to be symbols, but in Markdown
# everything is a string.
attr.transform_keys!(&:to_sym)
scope.link_to(content, link, attr)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/less.rb | middleman-core/lib/middleman-core/renderers/less.rb | module Middleman
module Renderers
# Sass renderer
class Less < ::Middleman::Extension
# A SassTemplate for Tilt which outputs debug messages
class DummyLessTemplate < ::Tilt::Template
def evaluate(scope, locals, &block)
raise <<~ERROR
The builtin less renderer has been removed from middleman.
To continue using less, make sure to setup an external pipeline.
See external pipeline documentation at https://middlemanapp.com/advanced/external-pipeline
for more information.
ERROR
end
end
::Tilt.register 'less', DummyLessTemplate
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/liquid.rb | middleman-core/lib/middleman-core/renderers/liquid.rb | # Require Gem
require 'liquid'
module Middleman
module Renderers
# Liquid Renderer
class Liquid < Middleman::Extension
# After config, setup liquid partial paths
def after_configuration
::Liquid::Template.file_system = self
end
# Called by Liquid to retrieve a template file
def read_template_file(template_path, _ = nil)
file = app.files.find(:source, "_#{template_path}.liquid")
raise ::Liquid::FileSystemError, "No such template '#{template_path}'" unless file
file.read
end
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
return resources unless app.extensions[:data]
resources.each do |resource|
next if resource.file_descriptor.nil?
next unless resource.file_descriptor[:full_path].to_s =~ %r{\.liquid$}
# Convert data object into a hash for liquid
resource.add_metadata locals: {
data: stringify_recursive(app.extensions[:data].data_store.to_h)
}
end
end
def stringify_recursive(hash)
{}.tap do |h|
hash.each { |key, value| h[key.to_s] = map_value(value) }
end
end
def map_value(thing)
case thing
when Hash
stringify_recursive(thing)
when Array
thing.map { |v| map_value(v) }
else
thing
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/markdown.rb | middleman-core/lib/middleman-core/renderers/markdown.rb | module Middleman
module Renderers
# Markdown renderer
class Markdown < ::Middleman::Extension
define_setting :markdown_engine, :kramdown, 'Preferred markdown engine'
define_setting :markdown_engine_prefix, ::Tilt, 'The parent module for markdown template engines'
# Once configuration is parsed
def after_configuration
markdown_exts = %w(markdown mdown md mkd mkdn)
begin
# Look for the user's preferred engine
if app.config[:markdown_engine] == :redcarpet
require 'middleman-core/renderers/redcarpet'
::Tilt.prefer(::Middleman::Renderers::RedcarpetTemplate, *markdown_exts)
elsif app.config[:markdown_engine] == :kramdown
require 'middleman-core/renderers/kramdown'
::Tilt.prefer(::Middleman::Renderers::KramdownTemplate, *markdown_exts)
elsif app.config[:markdown_engine]
# Map symbols to classes
markdown_engine_klass = if app.config[:markdown_engine].is_a? Symbol
engine = app.config[:markdown_engine].to_s
engine = engine == 'rdiscount' ? 'RDiscount' : engine.camelize
app.config[:markdown_engine_prefix].const_get("#{engine}Template")
else
app.config[:markdown_engine_prefix]
end
# Tell tilt to use that engine
::Tilt.prefer(markdown_engine_klass, *markdown_exts)
end
rescue LoadError
# If they just left it at the default engine and don't happen to have it,
# then they're using middleman-core bare and we shouldn't bother them.
if app.config.setting(:markdown_engine).value_set?
logger.warn "Requested Markdown engine (#{app.config[:markdown_engine]}) not found. Maybe the gem needs to be installed and required?"
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/coffee_script.rb | middleman-core/lib/middleman-core/renderers/coffee_script.rb | # Require gem
require 'coffee_script'
module Middleman
module Renderers
# CoffeeScript Renderer
class CoffeeScript < ::Middleman::Extension
# Setup extension
def initialize(app, options={}, &block)
super
# Tell Tilt to use it as well (for inline scss blocks)
::Tilt.register 'coffee', DebuggingCoffeeScriptTemplate
::Tilt.prefer(DebuggingCoffeeScriptTemplate)
DebuggingCoffeeScriptTemplate.middleman_app = app
end
# A Template for Tilt which outputs debug messages
class DebuggingCoffeeScriptTemplate < ::Tilt::CoffeeScriptTemplate
# Make the current Middleman app accessible to the template
cattr_accessor :middleman_app
def prepare
return super unless middleman_app.server?
@output = begin
super
rescue ::ExecJS::RuntimeError => e
e.to_s
rescue => e
e.to_s
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/redcarpet.rb | middleman-core/lib/middleman-core/renderers/redcarpet.rb | require 'redcarpet'
require 'active_support/core_ext/module/attribute_accessors'
module Middleman
module Renderers
class RedcarpetTemplate < ::Tilt::RedcarpetTemplate
# because tilt has decided to convert these
# in the wrong direction
ALIASES = {
escape_html: :filter_html
}.freeze
private
def _prepare_output
Redcarpet::Markdown.new(generate_renderer, options).render(data)
end
# Don't overload :renderer option with smartypants
# Support renderer-level options
def generate_renderer
if options.key?(:renderer)
renderer = options.delete(:renderer)
renderer.scope = options[:context] if renderer.respond_to?(:scope=)
return renderer
end
covert_options_to_aliases!
# Pick a renderer
renderer = MiddlemanRedcarpetHTML
renderer.scope = options[:context]
if options.delete(:smartypants)
# Support SmartyPants
renderer = Class.new(renderer) do
include ::Redcarpet::Render::SmartyPants
end
end
# Renderer Options
possible_render_opts = [:filter_html, :no_images, :no_links, :no_styles, :safe_links_only, :with_toc_data, :hard_wrap, :xhtml, :prettify, :link_attributes]
render_options = possible_render_opts.each_with_object({}) do |opt, sum|
sum[opt] = options.delete(opt) if options.key?(opt)
end
renderer.new(render_options)
end
def covert_options_to_aliases!
ALIASES.each do |aka, actual|
options[actual] = options.delete(aka) if options.key? aka
end
end
end
# Custom Redcarpet renderer that uses our helpers for images and links
class MiddlemanRedcarpetHTML < ::Redcarpet::Render::HTML
cattr_accessor :scope
def initialize(options={})
@local_options = options.dup
super
end
def image(link, title, alt_text)
if !@local_options[:no_images]
scope.image_tag(link, title: title, alt: alt_text)
else
link_string = link.dup
link_string << %("#{title}") if title && !title.empty? && title != alt_text
""
end
end
def link(link, title, content)
if !@local_options[:no_links]
attributes = { title: title }
attributes.merge!(@local_options[:link_attributes]) if @local_options[:link_attributes]
scope.link_to(content, link, attributes)
else
link_string = link.dup
link_string << %("#{title}") if title && !title.empty? && title != alt_text
"[#{content}](#{link_string})"
end
end
end
::Tilt.register RedcarpetTemplate, 'markdown', 'mkd', 'md'
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/erb.rb | middleman-core/lib/middleman-core/renderers/erb.rb | # ERb renderer
module Middleman
module Renderers
class ERb < ::Middleman::Extension
def after_configuration
::Tilt.prefer(Template, :erb)
end
class Template < ::Tilt::ErubiTemplate
def initialize(*args, &block)
super
@context = @options[:context]
end
##
# In preamble we need a flag `__in_erb_template` for padrino apps.
#
def precompiled_preamble(locals)
original = super
"__in_erb_template = true\n" << original
end
##
# Force the template the use the configured encoding.
#
def precompiled_template(locals)
if @context
super.dup.force_encoding(@context.app.config[:encoding])
else
super
end
end
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/haml.rb | middleman-core/lib/middleman-core/renderers/haml.rb | # Require gem
require 'haml'
# Require padrino-helpers now so that we get a chance to replace their renderer with ours in Tilt.
require 'padrino-helpers'
module SafeTemplate
def render(*)
super.html_safe
end
end
class Tilt::HamlTemplate
include SafeTemplate
end
module Middleman
module Renderers
# Haml precompiles filters before the scope is even available,
# thus making it impossible to pass our Middleman instance
# in. So we have to resort to heavy hackery :(
class HamlTemplate < ::Tilt::HamlTemplate
def initialize(*args, &block)
super
@context = @options[:context]
end
def prepare; end
def evaluate(scope, locals, &block)
options = {}.merge!(@options).merge!(context: @context || scope)
if options.include?(:outvar)
options[:buffer] = options.delete(:outvar)
options[:save_buffer] = true
end
if Object.const_defined?('::Haml::Template') # haml 6+
@engine = ::Haml::Template.new(eval_file, line, options) { data }
else
options[:filename] = eval_file
options[:line] = line
@engine = ::Haml::Engine.new(data, options)
end
output = @engine.render(scope, locals, &block)
output
end
end
# Haml Renderer
class Haml < ::Middleman::Extension
def initialize(app, options={}, &block)
super
if Object.const_defined?('::Haml::Options') # Haml 5 and older
::Haml::Options.defaults[:context] = nil
::Haml::Options.send :attr_accessor, :context
else # Haml 6+
::Haml::Engine.define_options context: nil
end
if defined?(::Haml::TempleEngine)
::Haml::TempleEngine.define_options context: nil
end
[::Haml::Filters::Sass, ::Haml::Filters::Scss, ::Haml::Filters::Markdown].each do |f|
f.class_exec do
if respond_to?(:template_class) # Haml 5 and older
def self.render_with_options(text, compiler_options)
modified_options = options.dup
modified_options[:context] = compiler_options[:context]
text = template_class.new(nil, 1, modified_options) { text }.render
super(text, compiler_options)
end
else # Haml 6+
def initialize(options = {})
super
@context = options[:context]
end
def compile_with_tilt(node, name, indent_width: 0)
options = { context: @context }
source = node.value[:text]
result = ::Tilt["t.#{name}"].new(nil, 1, options) { source }.render
temple = [:multi, [:static, result.gsub(/^/, ' ' * indent_width)]]
source.lines.size.times do
temple << [:newline]
end
temple
end
end
end
end
::Tilt.prefer(::Middleman::Renderers::HamlTemplate, :haml)
# Add haml helpers to context
::Middleman::TemplateContext.send :include, ::Haml::Helpers
end
def add_exposed_to_context(context)
super
context.init_haml_helpers if context.respond_to?(:init_haml_helpers)
end
end
end
end
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
middleman/middleman | https://github.com/middleman/middleman/blob/b497703afb715044bc5cfcd5616bd3825323505b/middleman-core/lib/middleman-core/renderers/sass_functions.rb | middleman-core/lib/middleman-core/renderers/sass_functions.rb | module Middleman
module Sass
module Functions
def asset_path(_source, _options)
# current_resource
end
# Using Middleman::Util#asset_path, return the full path
# for the given +source+ as a Sass String. This supports keyword
# arguments that mirror the +options+.
#
# === Examples
#
# background: url(image-path("image.jpg")); // background: url("/assets/image.jpg");
# background: url(image-path("image.jpg", $digest: true)); // background: url("/assets/image-27a8f1f96afd8d4c67a59eb9447f45bd.jpg");
#
def image_path(source, options={})
p = ::Middleman::Util.asset_path(middleman_context, :images, source.value, map_options(options))
::SassC::Script::Value::String.new p.to_s, :string
end
# Using Middleman::Util#asset_path, return the url CSS
# for the given +source+ as a Sass String. This supports keyword
# arguments that mirror the +options+.
#
# === Examples
#
# background: image-url("image.jpg"); // background: url("/assets/image.jpg");
# background: image-url("image.jpg", $digest: true); // background: url("/assets/image-27a8f1f96afd8d4c67a59eb9447f45bd.jpg");
#
def image_url(source, options={}, _cache_buster=nil)
# Work with the Sass #image_url API
if options.respond_to? :value
case options.value
when true
return image_path source
else
options = {}
end
end
::SassC::Script::Value::String.new "url(#{image_path(source, options)})"
end
# Using Middleman::Util#asset_path, return the full path
# for the given +source+ as a Sass String. This supports keyword
# arguments that mirror the +options+.
#
# === Examples
#
# src: url(font-path("font.ttf")); // src: url("/assets/font.ttf");
# src: url(font-path("font.ttf", $digest: true)); // src: url("/assets/font-27a8f1f96afd8d4c67a59eb9447f45bd.ttf");
#
def font_path(source, options={})
p = ::Middleman::Util.asset_path(middleman_context, :fonts, source.value, map_options(options))
::SassC::Script::Value::String.new p.to_s, :string
end
# Using Middleman::Util#asset_path, return the url CSS
# for the given +source+ as a Sass String. This supports keyword
# arguments that mirror the +options+.
#
# === Examples
#
# src: font-url("font.ttf"); // src: url("/assets/font.ttf");
# src: font-url("image.jpg", $digest: true); // src: url("/assets/font-27a8f1f96afd8d4c67a59eb9447f45bd.ttf");
#
def font_url(source, options={})
# Work with the Sass #font_url API
if options.respond_to? :value
case options.value
when true
return font_path source
else
options = {}
end
end
::SassC::Script::Value::String.new "url(#{font_path(source, options)})"
end
protected
# Returns a reference to Middleman's context through
# the importer.
def middleman_context # :nodoc:
options[:custom][:middleman_context]
end
# Returns a reference to Middleman's current resource.
def current_resource # :nodoc:
options[:custom][:current_resource]
end
# Returns an options hash where the keys are symbolized
# and the values are unwrapped Sass literals.
def map_options(options={}) # :nodoc:
# ::Sass::Util.map_hash(options) do |key, value|
# [key.to_sym, value.respond_to?(:value) ? value.value : value]
# end
options[:current_resource] = current_resource
options
end
end
end
end
::SassC::Script::Functions.send :include, ::Middleman::Sass::Functions
| ruby | MIT | b497703afb715044bc5cfcd5616bd3825323505b | 2026-01-04T15:39:40.166212Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.