Is it possible to use a ternary operator inside YAML with ERB, if so how?

257 Views Asked by At

I've been trying many syntax variations on the below but cannot get anything other than a syntax error (the simple erb interpolation works on its own, but the logical ternary operator throws a syntax error):

start_prompt: "Drum roll please \U0001F941\U0001F941\U0001F941.
    <%= active_player_name %> will <%= @new_game ? "begin" : "continue" %> play.
    Let the game commence \U0001F3AC. And may the best player win \U0001F3C6."

Any ideas on how I can get this to work? (I realise it'd be better practice to write such logic elsewhere, but a long story short in this context it's just easier here and no matter how good or bad a practice this is, I'd like to know how/whether this is possible anyway. Thanks

1

There are 1 best solutions below

2
user3402754 On

YAML doesn't support string interpolation in the same way that some other languages do. You may need to pre-process your YAML file in a ruby script, and then write the processed content to the YAML file.

Here's an example:

active_player_name = "John Doe"
new_game = true

yaml_content = <<~YAML
start_prompt: "Drum roll please \\U0001F941\\U0001F941\\U0001F941.
    #{active_player_name} will #{new_game ? "begin" : "continue"} play.
    Let the game commence \\U0001F3AC. And may the best player win \\U0001F3C6."
YAML

File.open('output.yaml', 'w') { |file| file.write(yaml_content) }

Alternatively, you can modify/substitute the string from the yaml file dynamically based on the conditions