File: file_creator.rb

package info (click to toggle)
ruby-jekyll-compose 0.12.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, forky, sid, trixie
  • size: 108 kB
  • sloc: ruby: 712; makefile: 3
file content (50 lines) | stat: -rw-r--r-- 1,070 bytes parent folder | download
1
2
3
4
5
6
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
# frozen_string_literal: true

module Jekyll
  module Compose
    class FileCreator
      attr_reader :file, :force, :root
      def initialize(file_info, force = false, root = nil)
        @file = file_info
        @force = force
        @root = root
      end

      def create!
        return unless create?

        ensure_directory_exists
        write_file
      end

      def file_path
        return file.path if root.nil? || root.empty?

        File.join(root, file.path)
      end

      private

      def create?
        return true if force
        return true unless File.exist?(file_path)

        Jekyll.logger.warn "A #{file.resource_type} already exists at #{file_path}"
        false
      end

      def ensure_directory_exists
        dir = File.dirname file_path
        FileUtils.mkdir_p(dir) unless Dir.exist?(dir)
      end

      def write_file
        File.open(file_path, "w") do |f|
          f.puts(file.content)
        end

        Jekyll.logger.info "New #{file.resource_type} created at #{file_path.cyan}"
      end
    end
  end
end