Skip to content

Commit 6bc2d1f

Browse files
committed
Refactor Generator to initialize with destination and content
1 parent a425fba commit 6bc2d1f

File tree

3 files changed

+25
-19
lines changed

3 files changed

+25
-19
lines changed

lib/boxing/generator.rb

+20-10
Original file line numberDiff line numberDiff line change
@@ -7,22 +7,32 @@ module Boxing
77
class Generator
88
include Utils
99

10+
# @since 0.11.0
11+
def initialize(destination, content)
12+
pp current_path
13+
@destination = current_path.join(destination)
14+
@content = content
15+
end
16+
1017
# Generate file
1118
#
1219
# @since 0.11.0
13-
def execute(destination, content = nil)
14-
content = yield if block_given?
15-
destination = current_path.join(destination)
16-
write(destination, content)
20+
def execute
21+
FileUtils.mkdir_p(File.dirname(@destination))
22+
File.write(@destination, render)
1723
end
1824

19-
# Write file to relative path
25+
# Render content
2026
#
21-
# @param [String] destination
22-
# @param [String] content
23-
def write(destination, content)
24-
FileUtils.mkdir_p(File.dirname(destination))
25-
File.write(destination, content)
27+
# @return [String]
28+
#
29+
# @since 0.11.0
30+
def render
31+
@render ||= if @content.is_a?(Proc)
32+
@content.call
33+
else
34+
@content
35+
end
2636
end
2737
end
2838
end

lib/boxing/utils.rb

+1-3
Original file line numberDiff line numberDiff line change
@@ -27,9 +27,7 @@ def current_path
2727
#
2828
# @since 0.11.0
2929
def template(destination, template, context: nil)
30-
Generator.new.execute(destination) do
31-
Template.new(template).render(context)
32-
end
30+
Generator.new(destination, -> { Template.new(template).render(context) }).execute
3331
end
3432
end
3533
end

spec/boxing/generator_spec.rb

+4-6
Original file line numberDiff line numberDiff line change
@@ -3,17 +3,15 @@
33
require 'tmpdir'
44

55
RSpec.describe Boxing::Generator do
6-
subject(:generator) { described_class.new }
6+
subject(:generator) { described_class.new('Dockerfile', 'test') }
77

88
let(:tmpdir) { Pathname.new(Dir.mktmpdir) }
99

10-
before do
11-
allow(generator).to receive(:current_path).and_return(tmpdir)
12-
13-
generator.execute('Dockerfile', 'test')
14-
end
10+
around { |example| Dir.chdir(tmpdir) { example.run } }
1511
after { FileUtils.remove_entry(tmpdir) }
1612

13+
before { generator.execute }
14+
1715
it 'creates a file' do
1816
expect(File.exist?(File.join(tmpdir, 'Dockerfile'))).to be true
1917
end

0 commit comments

Comments
 (0)