meshpi meshpi - 1 month ago 14
YAML Question

Reference YAML keyword file for DRY controller code

I want to be able to use globally accessible symbols throughout my rails app in order to print or return a set of easily maintainable strings/sentences. I've heard of a way using YAML before but I can't remember the specifics of it's implementation or what it's called.

An example how I ideally imagine it would work:

Controller



def foo
if token.expired?
render json: { message: :token_expiry_message }
end
end

def bar
if !user.authenticate
flash[:notice] = :token_expiry_message
end
end


Yaml file somewhere



token_expiry_message: "The user token is expired, please re-authenticate"


This way I can DRY up my controller code and use a standard language set throughout my app by referring them from the YAML file.

Answer

You can easily do this using built in internationalization stuff

http://guides.rubyonrails.org/i18n.html

in config/locals/locale.yml (Where locale is your current local such as en)..

 en:
     token_expiry_message: "Your token has expired, please get another"

then you can use just the t() helper. such has

  def foo
      if token.expired?
        render json: { message: t(:token_expiry_message) }
      end
    end

    def bar
      if !user.authenticate
        flash[:notice] = "Error: " + t(:token_expiry_message)
      end
    end

has the added benefit of being able to provide localized versions of the error messages.