ruby-on-railshamlmiddleman

Is there an easier way to write this down and prevent duplicate code?


I am using middleman (Ruby on Rails) with HAML.

I have code like this at the beginning of each page:

- if pageversion == "test"
   - domain = data.testvars.domain
   - action_url = data.testvars.openlocker_url
   - lockergroup = data.testvars.lockergroup

- else
  - domain = data.prdvars.domain
  - action_url = data.prdvars.openlocker_url
  - lockergroup = data.prdvars.lockergroup

but I want to know if it possible to do something like this:

domain = data.#{pageversion}vars.domain ...

so every time it parses #{pageversion} and uses the output to create either data.testvars.domain or data.prdvars.domain.

So I'd like to either specify which .yml file to use based on #{pageversion} or interpret the string before as part of the name of a variable to look in the correct file.

Any idea how to do this?

My current way of doing it involves a lot of duplicate code and trying to do it any other way has yielded errors only.


Solution

  • You need to pre-assign the correct one, before using it:

    data_vars = pageversion == "test" ? data.testvars : data.prdvars
    

    Then you can use assigned value without dublicate code:

    domain = data_vars.domain
    action_url = data_vars.openlocker_url
    lockergroup = data_vars.lockergroup