Class: Dato::Dump::Operation::AddToDataFile

Inherits:
Object
  • Object
show all
Defined in:
lib/dato/dump/operation/add_to_data_file.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(context, path, format, value) ⇒ AddToDataFile

Returns a new instance of AddToDataFile.



11
12
13
14
15
16
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 11

def initialize(context, path, format, value)
  @context = context
  @path = path
  @format = format
  @value = value
end

Instance Attribute Details

#contextObject (readonly)

Returns the value of attribute context.



9
10
11
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 9

def context
  @context
end

#formatObject (readonly)

Returns the value of attribute format.



9
10
11
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 9

def format
  @format
end

#pathObject (readonly)

Returns the value of attribute path.



9
10
11
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 9

def path
  @path
end

#valueObject (readonly)

Returns the value of attribute value.



9
10
11
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 9

def value
  @value
end

Instance Method Details

#performObject



18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dato/dump/operation/add_to_data_file.rb', line 18

def perform
  complete_path = File.join(context.path, path)
  FileUtils.mkdir_p(File.dirname(complete_path))

  content_to_add = Format.dump(format, value)

  old_content = if File.exist? complete_path
                  ::File.read(complete_path)
                else
                  ""
                end

  new_content = old_content.sub(
    /\n*(#\s*datocms:start.*#\s*datocms:end|\Z)/m,
    "\n\n# datocms:start\n#{content_to_add}\n# datocms:end",
  )

  File.open(complete_path, "w") do |f|
    f.write new_content
  end
end