middleman/middleman-core/lib/middleman-core/core_extensions/front_matter.rb

79 lines
2.2 KiB
Ruby
Raw Normal View History

2015-06-17 00:30:37 +02:00
# Core Pathname library used for traversal
require 'pathname'
2015-06-17 00:30:37 +02:00
# DbC
require 'middleman-core/contracts'
require 'active_support/core_ext/hash/keys'
2015-06-17 00:30:37 +02:00
require 'middleman-core/util/data'
# Extensions namespace
module Middleman::CoreExtensions
class FrontMatter < ::Middleman::Extension
2014-05-31 07:32:39 +02:00
# Try to run after routing but before directory_indexes
self.resource_list_manipulator_priority = 90
def initialize(app, options_hash={}, &block)
super
@cache = {}
end
def before_configuration
2014-12-23 23:54:21 +01:00
app.files.on_change(:source, &method(:clear_data))
end
2014-07-03 04:04:34 +02:00
# @return Array<Middleman::Sitemap::Resource>
Contract ResourceList => ResourceList
def manipulate_resource_list(resources)
resources.each do |resource|
next if resource.file_descriptor.nil?
fmdata = data(resource.file_descriptor[:full_path].to_s).first.dup
# Copy over special options
2014-04-28 08:21:12 +02:00
# 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)
2014-05-31 08:19:33 +02:00
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)
2011-11-28 07:04:19 +01:00
# TODO: Save new template here somewhere?
end
end
2013-12-28 19:14:15 +01:00
2014-01-02 06:19:05 +01:00
# Get the template data from a path
# @param [String] path
# @return [String]
2014-07-16 03:01:45 +02:00
Contract String => Maybe[String]
2014-01-02 06:19:05 +01:00
def template_data_for_file(path)
data(path).last
end
2014-07-03 04:04:34 +02:00
Contract String => [Hash, Maybe[String]]
def data(path)
2014-07-16 03:01:45 +02:00
file = app.files.find(:source, path)
2014-07-16 03:01:45 +02:00
return [{}, nil] unless file
2015-06-17 00:30:37 +02:00
@cache[file[:full_path]] ||= ::Middleman::Util::Data.parse(file[:full_path])
2014-07-16 03:01:45 +02:00
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])
end
end
end
end