Module: Jekyll::DocumentWriter

Defined in:
lib/jekyll/document_writer.rb

Class Method Summary collapse

Class Method Details

.included(base) ⇒ Object



7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
# File 'lib/jekyll/document_writer.rb', line 7

def self.included(base)
  base.class_eval do
    # Writes changes to the file and adds it to git staged changes
    def save
      return unless data.fetch('save', true)

      Jekyll.logger.debug 'Writing', path

      file = File.open(path, File::RDWR | File::CREAT, 0o640) do |f|
        f.flock(File::LOCK_EX)
        f.rewind

        f.write(sanitized_data.to_yaml)
        f.write("---\n\n")
        f.write(content)

        f.flush
        f.truncate(f.pos)
      end

      site.staged_files << real_path if file.zero?

      file.zero?
    end

    # Resolves the real path for the document
    # @return [String]
    def real_path
      @real_path ||= Pathname.new(relative_path).realpath.relative_path_from(site.source).to_s
    end

    # Prepares the data for dumping, by excluding some keys and
    # transforming other Documents replaced by jekyll-linked-posts.
    #
    # @return [Hash]
    def sanitized_data
      data.reject do |k, _|
        excluded_attributes.include? k
      end.transform_values do |value|
        case value
        when Jekyll::Document
          value.data['uuid']
        when Jekyll::Convertible
          value.data['uuid']
        when Set
          value.map do |v|
            v.respond_to?(:data) ? v.data['uuid'] : v
          end
        when Array
          value.map do |v|
            v.respond_to?(:data) ? v.data['uuid'] : v
          end
        when Hash
          value.transform_values do |v|
            v.respond_to?(:data) ? v.data['uuid'] : v
          end
        else
          value
        end
      end
    end

    def excluded_attributes
      @excluded_attributes ||= %w[slug ext date excerpt]
    end
  end
end