2

I have an abstract class WcagElement, and several derived classes that share the same model name so I can share the views, routes, etc. between all of them:

class WcagElement < ApplicationRecord
  # See https://stackoverflow.com/questions/4507149/best-practices-to-handle-routes-for-sti-subclasses-in-rails/13131811
  def self.model_name
    ActiveModel::Name.new(self, nil, 'WcagElement') # Make sure that STI models use the same namespace
  end
end

class WcagPrinciple < WcagElement
end

class WcagGuideline < WcagElement
end

class WcagCriterion < WcagElement
end

This works very well.

The only problem I have is that in some views, I need to display the translated human model name of a derived class.

At the time, because I override self.model_name in the abstract class, I get the same model name for each model:

$ WcagPrinciple.model_name.human => WCAG Element
$ WcagGuideline.model_name.human => WCAG Element
$ WcagCriterion.model_name.human => WCAG Element

I have added the relevant keys to the translation file:

wcag_criterion:
  one: Criterion
  other: Criteria
wcag_element:
  one: WCAG element
  other: WCAG elements
wcag_guideline:
  one: Guideline
  other: Guideline
wcag_principle:
  one: Principle
  other: Principles

I tried messing around with creating a sti_model_name method:

# In WcagPrinciple
def sti_model_name # Or better self.sti_model_name?
  ActiveModel::Name.new(self, nil, 'WcagPrinciple')
end

But $ WcagPrinciple.sti_model_name.human results in Wcag principle (instead of WCAG Principle), which is a generically created human name, not the one in the translation file.

I also tried to alias the old self.model_name, but didn't succeed.

Thanks for help.

Joshua Muheim
  • 12,617
  • 9
  • 76
  • 152

0 Answers0