1
module ApplicationHelper
  def t(*a)
    translate(*a)
  end
end

Case 1 :- t('views.home.welcome_updated', default: 'Updated') => Getting Error: (wrong number of arguments (given 2, expected 1))

Case 2 :- t('views.welcome') => Working fine

Ruby Version: 3.0.6
Rails Version: 6.1.7.6

What is the problem with above code?

Both case 1 & 2 working fine in ruby 2.7. i am getting error after upgraded ruby version to 3

customize t method to

module ApplicationHelper
  def t(key, **options)
    args = [key]
    args.push options if options.present?
    translate(*a)
  end
end

But this is also not working

2
  • 1
    The method's signature is translate(key, **options) but your *a only captures positional arguments, i.e. the key part. In Ruby 3.x, you have to handle keyword arguments explicitly via ** or use ... as shown below. Commented Nov 20, 2023 at 10:50
  • BTW, Rails' TranslationHelper defines both, translate and t, so maybe you already have both variants and are needlessly re-defining t. Commented Nov 20, 2023 at 10:54

1 Answer 1

5

When you want to forward all arguments, not matter of their structure, then you can use the ... syntax, like this:

module ApplicationHelper
  def t(...)
    translate(...)
  end
end

Or, when do not need to manipulate the arguments before forwarding to the original method or to act on the response before returning, then you can alias the method name like this:

alias_method :t, :translate
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.