How to avoid generating content with quotes from an erb template?

Viewed 192

I have written an erb template which I'm using to generate a Dockerfile dynamically. Here is how the whole thing works:

  1. Take the input from command line.
  2. Create an ruby array out of the input.
  3. Use the Dockerfile.erb to generate Dockerfile based of this input.

The problem that I face here is that when the input is copied onto the generated Dockerfile, it has quotes around it which I need to avoid. Is there a way to do so?

Dockerfile.erb

FROM docker.cernerrepos.net/alpine:3.7 AS builder

LABEL bundles=<%= keys[:bundles] %>

generate.rb

require 'optparse'
require 'erb'

DEBUG_PREFIX = '>>> generate_dockerfile.rb ->'

@options = {}
@options[:output]= '.'

optparse = OptionParser.new do |opts|
  opts.banner = 'Usage: generate_dockerfile.rb [options]'
  opts.on('-b [BUNDLES]', '--bundles [BUNDLES]', "Comma separated list of bundles without extension and version.") do |bundles|
    @options[:bundles] = bundles.split(',')
  end
  opts.on('-h', '--help', 'Display this Help') do
    puts opts
    exit
  end
end

optparse.parse!

keys = @options

File.open('Dockerfile', 'w+') do |f|
  f.write(ERB.new(File.read('Dockerfile.erb'), nil, '-').result(binding))
end

Actual Output Dockerfile

FROM docker.cernerrepos.net/alpine:3.7 AS builder

LABEL bundles=["sample_bundle1", "sample_bundle2"]

Expected Output Dockerfile

FROM docker.cernerrepos.net/alpine:3.7 AS builder

LABEL bundles=[sample_bundle1, sample_bundle2]

Command to Execute

ruby generate.rb -b sample_bundle1,sample_bundle2

Edit 1: Modified the question to include the minimum sample code, the expected out and the actual output and the command to run the code.

1 Answers

Right here:

LABEL bundles=<%= keys[:bundles] %>

You are basically calling keys[:bundle].to_s and interpolating that in the result.

What's ["foo", "bar"].to_s? It's ["foo", "bar"] (with quotes!)

That's why you're getting this result.

You can change it to the following, if you want to remove the quotations:

LABEL bundles=[<%= keys[:bundles].join(", ") %>]

Not to say this is the wrong approach, but isn't really a typical thing to do, so I don't think there's another built-in way to do this.

Related