lib/bunto/document.rb in bunto-3.0.0 vs lib/bunto/document.rb in bunto-3.2.1

- old
+ new

@@ -5,13 +5,13 @@ include Comparable attr_reader :path, :site, :extname, :collection attr_accessor :content, :output - YAML_FRONT_MATTER_REGEXP = /\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)/m - DATELESS_FILENAME_MATCHER = /^(.+\/)*(.*)(\.[^.]+)$/ - DATE_FILENAME_MATCHER = /^(.+\/)*(\d+-\d+-\d+)-(.*)(\.[^.]+)$/ + YAML_FRONT_MATTER_REGEXP = %r!\A(---\s*\n.*?\n?)^((---|\.\.\.)\s*$\n?)!m + DATELESS_FILENAME_MATCHER = %r!^(?:.+/)*(.*)(\.[^.]+)$! + DATE_FILENAME_MATCHER = %r!^(?:.+/)*(\d+-\d+-\d+)-(.*)(\.[^.]+)$! # Create a new Document. # # path - the path to the file # relations - a hash with keys :site and :collection, the values of which @@ -49,28 +49,28 @@ # Merge some data in with this document's data. # # Returns the merged data. def merge_data!(other, source: "YAML front matter") - if other.key?('categories') && !other['categories'].nil? - if other['categories'].is_a?(String) - other['categories'] = other['categories'].split(" ").map(&:strip) + if other.key?("categories") && !other["categories"].nil? + if other["categories"].is_a?(String) + other["categories"] = other["categories"].split(" ").map(&:strip) end - other['categories'] = (data['categories'] || []) | other['categories'] + other["categories"] = (data["categories"] || []) | other["categories"] end Utils.deep_merge_hashes!(data, other) - if data.key?('date') && !data['date'].is_a?(Time) - data['date'] = Utils.parse_date( - data['date'].to_s, + if data.key?("date") && !data["date"].is_a?(Time) + data["date"] = Utils.parse_date( + data["date"].to_s, "Document '#{relative_path}' does not have a valid date in the #{source}." ) end data end def date - data['date'] ||= (draft? ? source_file_mtime : site.time) + data["date"] ||= (draft? ? source_file_mtime : site.time) end def source_file_mtime @source_file_mtime ||= File.mtime(path) end @@ -79,19 +79,21 @@ # the document is in the 'posts' collection but in a different # directory than '_posts'. # # Returns whether the document is a draft. def draft? - data['draft'] ||= relative_path.index(collection.relative_directory).nil? && collection.label == "posts" + data["draft"] ||= relative_path.index(collection.relative_directory).nil? && + collection.label == "posts" end # The path to the document, relative to the site source. # # Returns a String path which represents the relative path # from the site source to this document def relative_path - @relative_path ||= Pathname.new(path).relative_path_from(Pathname.new(site.source)).to_s + @relative_path ||= Pathname.new(path) + .relative_path_from(Pathname.new(site.source)).to_s end # The output extension of the document. # # Returns the output extension @@ -101,11 +103,11 @@ # The base filename of the document, without the file extname. # # Returns the basename without the file extname. def basename_without_ext - @basename_without_ext ||= File.basename(path, '.*') + @basename_without_ext ||= File.basename(path, ".*") end # The base filename of the document. # # Returns the base filename of the document. @@ -154,11 +156,11 @@ # Determine whether the document is a CoffeeScript file. # # Returns true if extname == .coffee, false otherwise. def coffeescript_file? - '.coffee'.eql?(extname) + ".coffee" == extname end # Determine whether the file should be rendered with Liquid. # # Returns false if the document is either an asset file or a yaml file, @@ -193,21 +195,21 @@ # The permalink for this Document. # Permalink is set via the data Hash. # # Returns the permalink or nil if no permalink was set in the data. def permalink - data && data.is_a?(Hash) && data['permalink'] + data && data.is_a?(Hash) && data["permalink"] end # The computed URL for the document. See `Bunto::URL#to_s` for more details. # # Returns the computed URL for the document. def url @url = URL.new({ - :template => url_template, + :template => url_template, :placeholders => url_placeholders, - :permalink => permalink + :permalink => permalink }).to_s end def [](key) data[key] @@ -235,22 +237,21 @@ # # Returns nothing. def write(dest) path = destination(dest) FileUtils.mkdir_p(File.dirname(path)) - File.open(path, 'wb') do |f| - f.write(output) - end + File.write(path, output, :mode => "wb") trigger_hooks(:post_write) end # Whether the file is published or not, as indicated in YAML front-matter # - # Returns true if the 'published' key is specified in the YAML front-matter and not `false`. + # Returns 'false' if the 'published' key is specified in the + # YAML front-matter and is 'false'. Otherwise returns 'true'. def published? - !(data.key?('published') && data['published'] == false) + !(data.key?("published") && data["published"] == false) end # Read in the file and assign the content and data based on the file contents. # Merge the frontmatter of the file with the frontmatter default # values @@ -261,47 +262,48 @@ if yaml_file? @data = SafeYAML.load_file(path) else begin - defaults = @site.frontmatter_defaults.all(relative_path, collection.label.to_sym) - merge_data!(defaults, source: "front matter defaults") unless defaults.empty? + defaults = @site.frontmatter_defaults.all( + relative_path, + collection.label.to_sym + ) + merge_data!(defaults, :source => "front matter defaults") unless defaults.empty? self.content = File.read(path, Utils.merged_file_read_opts(site, opts)) if content =~ YAML_FRONT_MATTER_REGEXP self.content = $POSTMATCH data_file = SafeYAML.load(Regexp.last_match(1)) - merge_data!(data_file, source: "YAML front matter") if data_file + merge_data!(data_file, :source => "YAML front matter") if data_file end post_read rescue SyntaxError => e Bunto.logger.error "Error:", "YAML Exception reading #{path}: #{e.message}" - rescue Exception => e - if e.is_a? Bunto::Errors::FatalException - raise e - end + rescue => e + raise e if e.is_a? Bunto::Errors::FatalException Bunto.logger.error "Error:", "could not read file #{path}: #{e.message}" end end end def post_read if relative_path =~ DATE_FILENAME_MATCHER - date, slug, ext = $2, $3, $4 - if !data['date'] || data['date'].to_i == site.time.to_i - merge_data!({"date" => date}, source: "filename") + date, slug, ext = Regexp.last_match.captures + if !data["date"] || data["date"].to_i == site.time.to_i + merge_data!({ "date" => date }, :source => "filename") end elsif relative_path =~ DATELESS_FILENAME_MATCHER - slug, ext = $2, $3 + slug, ext = Regexp.last_match.captures end # Try to ensure the user gets a title. data["title"] ||= Utils.titleize_slug(slug) # Only overwrite slug & ext if they aren't specified. - data['slug'] ||= slug - data['ext'] ||= ext + data["slug"] ||= slug + data["ext"] ||= ext populate_categories populate_tags generate_excerpt end @@ -310,20 +312,23 @@ # In the case of es/_posts, 'es' is added as a category. # In the case of _posts/es, 'es' is NOT added as a category. # # Returns nothing. def categories_from_path(special_dir) - superdirs = relative_path.sub(/#{special_dir}(.*)/, '').split(File::SEPARATOR).reject do |c| + superdirs = relative_path.sub(%r!#{special_dir}(.*)!, "") + .split(File::SEPARATOR) + .reject do |c| c.empty? || c.eql?(special_dir) || c.eql?(basename) end - merge_data!({ 'categories' => superdirs }, source: "file path") + merge_data!({ "categories" => superdirs }, :source => "file path") end def populate_categories merge_data!({ - 'categories' => ( - Array(data['categories']) + Utils.pluralized_array_from_hash(data, 'category', 'categories') + "categories" => ( + Array(data["categories"]) + + Utils.pluralized_array_from_hash(data, "category", "categories") ).map(&:to_s).flatten.uniq }) end def populate_tags @@ -349,22 +354,22 @@ # The string representation for this document. # # Returns the content of the document def to_s - output || content || 'NO CONTENT' + output || content || "NO CONTENT" end # Compare this document against another document. # Comparison is a comparison between the 2 paths of the documents. # # Returns -1, 0, +1 or nil depending on whether this doc's path is less than, # equal or greater than the other doc's path. See String#<=> for more details. def <=>(other) return nil unless other.respond_to?(:data) - cmp = data['date'] <=> other.data['date'] - cmp = path <=> other.path if cmp.nil? || cmp == 0 + cmp = data["date"] <=> other.data["date"] + cmp = path <=> other.path if cmp.nil? || cmp.zero? cmp end # Determine whether this document should be written. # Based on the Collection to which it belongs. @@ -378,11 +383,11 @@ # The Document excerpt_separator, from the YAML Front-Matter or site # default excerpt_separator value # # Returns the document excerpt_separator def excerpt_separator - (data['excerpt_separator'] || site.config['excerpt_separator']).to_s + (data["excerpt_separator"] || site.config["excerpt_separator"]).to_s end # Whether to generate an excerpt # # Returns true if the excerpt separator is configured. @@ -392,31 +397,27 @@ def next_doc pos = collection.docs.index { |post| post.equal?(self) } if pos && pos < collection.docs.length - 1 collection.docs[pos + 1] - else - nil end end def previous_doc pos = collection.docs.index { |post| post.equal?(self) } if pos && pos > 0 collection.docs[pos - 1] - else - nil end end def trigger_hooks(hook_name, *args) Bunto::Hooks.trigger collection.label.to_sym, hook_name, self, *args if collection Bunto::Hooks.trigger :documents, hook_name, self, *args end def id - @id ||= File.join(File.dirname(url), (data['slug'] || basename_without_ext).to_s) + @id ||= File.join(File.dirname(url), (data["slug"] || basename_without_ext).to_s) end # Calculate related posts. # # Returns an Array of related Posts. @@ -431,11 +432,12 @@ end # Override of method_missing to check in @data for the key. def method_missing(method, *args, &blck) if data.key?(method.to_s) - Bunto.logger.warn "Deprecation:", "Document##{method} is now a key in the #data hash." - Bunto.logger.warn "", "Called by #{caller.first}." + Bunto::Deprecator.deprecation_message "Document##{method} is now a key "\ + "in the #data hash." + Bunto::Deprecator.deprecation_message "Called by #{caller.first}." data[method.to_s] else super end end