Tom
Tom

Reputation: 1105

Ruby regex in Yaml

I'm new to YAML and I'm experimenting with writing some tests for language translation. The idea being that I have a YAML file that has the English and Welsh versions of the same text. I was wondering how I might do the following use a regex within the string in the YAML?

Example:

I have this basic test:

#Gherkin
And I expect to see payment confirmation for "Dave"

#Step Def
    And /^I expect to see payment confirmation for "(.*?)"$/ do |user|
      expect(page).to have_text "Payment successful for #{user} - Reference: 000000"
end

YAML Entry:

"Payment successful for Dave reference: 000000"
 - welsh: "Taliad llwyddiannus ar gyfer Dave Cyfeirnod: 000000"

Could I parameterize Dave in that YAML entry as the test suite covers hundreds of users.

Thanks

Upvotes: 1

Views: 711

Answers (1)

Stanko
Stanko

Reputation: 520

If you want to interpolate text into YAML you will need to replace the words that you want to be interpolated with %{keyword} where the keyword is a key that will be used to indicate which data to interpolate there.

If you use Rails, you would use the t helper method as outlined in this section of the I18n guide.

# The YAML file
en:
  payment_succeeded: "Payment successful for %{first_name} reference: %{reference_number}"
wh: 
  payment_succeeded: "Taliad llwyddiannus ar gyfer %{first_name} Cyfeirnod: %{reference_number}"

# Rails Controller / View / Model
t(:payment_succeeded, first_name: 'Dave', reference_number: '000000')

If you want a pure ruby implementation you can use the Kernel::format method.

# The YAML file
# NOTE: This can be in any format, as long as you use %{keyword} in places where you want the data to be interpolated
translations:
  english: "Payment successful for %{first_name} reference: %{reference_number}"
  welsh: "Taliad llwyddiannus ar gyfer %{first_name} Cyfeirnod: %{reference_number}"

# Ruby
translations = YAML.load(File.read('translations.yaml'))
string = format(translations[:translations][:welsh], first_name: 'Dave', reference_number: '000000')

Hope this helps.

Upvotes: 5

Related Questions