Can I set a constant at compile time?

In the following:

Can I (alternatively) set the value of RUCKSACK_MODE at compile time, with :
crystal build ./src/rucksack.cr --define RUCKSACK_MODE=0


require "http/server"
require "rucksack"

RUCKSACK_MODE = 1

# Archiving mode
p "RUCKSACK_MODE =  #{RUCKSACK_MODE}"

# local server set and run:
server = HTTP::Server.new do |context|
  path = context.request.path
  path = "/index.html" if path == "/"
  path = "./webroot#{path}"

  begin
    rucksack(path).read(context.response.output)
  rescue Rucksack::FileNotFound
    context.response.status = HTTP::Status.new(404)
    context.response.print "404 not found :("
  end
end

address = server.bind_tcp 8080
puts "Listening on http://#{address}"
server.listen

# Set the local dir:
{% for name in `find ./webroot -type f`.split('\n') %}
      rucksack({{name}})
{% end %}

Probably be a good use case for an ENV var. RUCKSACK_MODE=0 ./rucksack. Tho you will have to convert it to the proper type as it’ll always be a String.

Thanks, but does

ENV var. RUCKSACK_MODE=0

go into the .cr code or on the command-line?

The idea is to set the constant at compile time via a Makefile:

# Makefile

dev : src/rucksack.cr 
	crystal build ./src/rucksack.cr --define MODE=0


exe : rc/rucksack.cr 
	crystal build ./src/rucksack.cr --define MODE=1
	cat .rucksack >>rucksack

release : rc/rucksack.cr
	crystal build --release ./src/rucksack.cr  --define MODE=2
	cat .rucksack >>rucksack


test : rc/rucksack.cr
	mkdir tst
	cp ./rucksack ./tst/rucksack
	./tst/rucksack

It could either be something that controls the value at compile time, or runtime depending on when you access the value of the ENV var. For example given a program like:

COMPILE_TIME_CONST = {{ env("RUCKSACK_MODE").to_i }}
RUNTIME_CONST      = ENV["RUCKSACK_MODE"].to_i

pp COMPILE_TIME_CONST
pp RUNTIME_CONST
RUCKSACK_MODE=1 crystal build test.cr
RUCKSACK_MODE=2 ./test
# 1
# 2
RUCKSACK_MODE=3 ./test
# 1
# 3
3 Likes