Search code examples
ruby-on-railsrubyruby-on-rails-4rails-i18n

Why people mostly wrap I18n.t method instead of delegating?


I see many examples of

def t(*args)
  I18n.t(*args)
end

and very few

delegate :t, to: I18n

In my honest opinion second solution is semantically better. Why people tend to not use it?


Solution

  • Why people tend to not use it?

    Well, one reason (as mentioned by @BroiSatse) is that people simply don't know about this technique.

    From bytecode point of view, there is little difference. delegate generates roughly the same method, with a few additional checks for safety (respond_to?, etc.)

    We, in our team, have this rule: delegate should be used to give a hint to external callers that methods are being forwarded to some other object. As a consequence, it should not be used just for "shortening" internal invocations of delegated methods. That is, if a method is not called from outside, don't use delegate on it, write the forwarding yourself.

    So the choice is based on the message that we want to convey. And yes, we have both forms of delegation to I18n.t in our app :)

    For example:

    # use `delegate`, method is called from outside
    class User
      has_one :address
    
      delegate :country, to: :address
    end
    
    <%= user.country %>
    
    
    # only internal callers, do not use `delegate`
    class Exporter
      # delegate :export, to: :handler 
      def call
        handler.export
      end
    
      private
    
      def handler
        return something_with_export_method
      end
    end