Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use i18n translate method with Draper gem?

I use Draper gem to decorate my models. Here I have pretty classic settings:

# app/decorators/subject_decorator.rb
class SubjectDecorator < ApplicationDecorator
  decorates :subject

  def edit_link
    h.link_to(h.t('.edit'), '#')
  end
end

I use i18n for internationalization. But when I run this, I get:

Cannot use t(".edit") shortcut because path is not available

So I was wondering if anyone has done this before? It should be pretty straight forward.

like image 517
Pierre-Louis Gottfrois Avatar asked Dec 04 '22 19:12

Pierre-Louis Gottfrois


1 Answers

The problem is you can't take advantage of lazy lookup in decorators because they don't have any context to determine the view file level (index, show, edit, etc.). So out of the box you just need to spell out the whole thing like t('subjects.show.edit') or whatever.

Here's what I wound up doing to get it somewhat working for me.

class ApplicationDecorator < Draper::Base
  def translate(key, options={})
    if key.to_s[0] == '.'
      key = model_class.to_s.downcase.pluralize + key
    end

    I18n.translate(key, options)
  end
  alias :t :translate
end

This won't get you the full subjects.show.edit reference, you'll just get subjects.edit but it seemed better than nothing to me.

like image 103
aNoble Avatar answered Dec 22 '22 05:12

aNoble