1

As you can see this isn't very DRY:

en:
  dashboard_policy:
    statistics?: 'You cannot access the statistics panel because you are not an admin!content'
    forums?: 'You cannot access the forums panel because you are not an admin!'
    browser?: 'You cannot access the browser panel because you are not an admin!'
    users?: 'You cannot access the users panel because you are not an admin!'

It is possible to have methods or variables inside YAML, in order to stop repeating myself?

Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
Starkers
  • 10,273
  • 21
  • 95
  • 158

2 Answers2

2

Use Anchors and Alias Nodes

You can't use variables within YAML directly, although you can embed them in strings for your program code to interpolate. However, you can DRY up YAML a lot using anchors and alias nodes. For example:

en:
  warn_not_admin: &warn_not_admin
    "You can't access this panel because you aren't an admin."                        
  dashboard_policy:
    statistics?: *warn_not_admin
    forums?:     *warn_not_admin
    browser?:    *warn_not_admin
    users?:      *warn_not_admin

This defines an anchor named warn_not_admin, assigns it to the value of the :warn_not_admin key, and then references that node in each child element of the :dashboard_policy key.

Note that in this particular case, we reuse the same message. This adds a little more DRY-ness by assuming that your users know which panel they're dealing with. If they really need to be told which panel the message refers to, using interpolation within your code (as described by this other answer) might be a reasonable alternative.

Community
  • 1
  • 1
Todd A. Jacobs
  • 81,402
  • 15
  • 141
  • 199
  • This ignores the message differences. – Dave Newton Sep 15 '14 at 16:46
  • @DaveNewton Yup. If you want interpolation, Lucas has a [reasonable answer](http://stackoverflow.com/a/25852762/1301972). Personally, I'd rather see the message changed to "You can't access this panel because you aren't an admin." and keep it really DRY. YMMV. – Todd A. Jacobs Sep 15 '14 at 16:49
1

You cannot use variables in yml other than reusing whole value or passing variables to tranlations by using %{variable} notation.

So in your case I would write something like:

en:
  dashboard_policy:
    access_denied: 'You cannot access the %{location} because you are not an admin!'
  locations:
    forums: "forums panel"
    ...

Then in your view i.e.:

<%= t('dashboard_policy.access_denied', location: t('locations.forums')) %>
Lucas
  • 2,587
  • 1
  • 18
  • 17
  • This is a reasonable answer, but the interpolation then happens in the code, not in the YAML. It's a distinction worth noting; you *did* note it, but I'm just clarifying it a little for future visitors. – Todd A. Jacobs Sep 15 '14 at 16:44