Reputation:
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:
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
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.
Upvotes: 0
Views: 139
Reputation: 20232
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.
Upvotes: 2
Reputation: 1486
Yes, you can use a Settings.yml file for this. You can also get deeper into it and use localization files if you need to support multiple languages.
In your Settings.yml:
token_expiry_message: 'The user token is expired, please re-authenticate'
This can then be loaded into your code via:
def foo
if token.expired?
render json: { message: Settings.token_expiry_message }
end
end
def bar
if !user.authenticate
flash[:notice] = "Error: #{Settings.token_expiry_message}"
end
end
Upvotes: 0