https://avo.cool logo
Automatically Translate help messages
# tips-and-tricks
l
Is there a way to use "avo.en.resources.yml" to localise "help" values when declaring fields? Trying to avoid setting up I18n.t explicitly
l
Off the top of my head… no. I’d have to check the code and I’m AFK. But that’s a great idea. Those would apply per field id, right? Eg: field :first_name and the key is first_name
l
Yup. I hacked something like this:
Copy code
ruby
module Localization
  extend ActiveSupport::Concern

  # Returns a lambda for field help text (evaluated in field context)
  # Usage: help: field_help(:guest_email)
  def field_help(field_name, **interpolations)
    # Capture the translation key outside the lambda
    translation_key = field_translation_key(field_name, :help)
    -> { I18n.t(translation_key, **interpolations) }
  end

  # Returns a string for field placeholder
  # Usage: placeholder: field_placeholder(:comment)
  def field_placeholder(field_name, **interpolations)
    I18n.t(field_translation_key(field_name, :placeholder), **interpolations)
  end

  private

  def field_translation_key(field_name, key)
    # Get the full class name and extract just the resource part
    # e.g., "Avo::Resources::BlockedPeriodOwnerStay" => "blocked_period_owner_stay"
    # Note: We use to_s instead of name because Avo overrides the name method
    resource_name = self.class.to_s.split('::').last.underscore
    "avo.resources.#{resource_name}.fields.#{field_name}.#{key}"
  end
end
Copy code
ruby
help: field_help(:guest_type))
But would be nicer to have something more avo-native ofc 🙂
l
I agree. Convention over configuration
You can take it further by overriding the field method
And add a new kwarg help_for: :guest_type
I’m AFK, otherwise I would hack something together 😛
something like that in your base resource
Copy code
ruby
module Avo
  class BaseResource < Avo::Resources::Base
    # Users can override this class to add custom methods for all resources.
    # in Avo::BaseResource
    def field(field_name, *args, help_for: nil, **kwargs, &block)
      if help_for.present?
        help_for_key = help_for || field_name
        kwargs[:help] = -> { I18n.t("avo.resources.#{resource_name}.fields.#{field_name}.#{help_for_key}") }
      end

      super(field_name, *args, **kwargs, &block)
    end
  end
end
and now you can use it like
field :guest_type, as: :text, help_for: :guest_type
or omit it altogether and have that built-in