Skip to content

Instantly share code, notes, and snippets.

@buren
Created July 10, 2015 18:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save buren/56912b4ee6d7e1d6aea7 to your computer and use it in GitHub Desktop.
Save buren/56912b4ee6d7e1d6aea7 to your computer and use it in GitHub Desktop.
Generate translations for activerecord models and columns
class I18nGenerator
attr_reader :models, :lang_code
def initialize(lang_code: :en)
ignored_tables = %w(schema_migrations)
@models = ActiveRecord::Base.connection.tables - ignored_tables
@models.map! { |model| model.singularize.camelize.constantize }
@lang_code = lang_code.to_s
end
def self.write(*args)
new(*args).write
end
def write
File.write("config/locales/#{lang_code}.activerecord.yml", i18n_yaml)
end
private
def i18n_yaml
translations = build_translations
{
lang_code => {
'activerecord' => {
'models' => translations[:models],
'attributes' => translations[:attributes]
}
}
}.to_yaml
end
def build_translations
model_t = {}
attributes_t = {}
models.each do |model|
underscored = model.to_s.underscore
model_t.merge!(model_attributes(underscored))
attributes_t.merge!(underscored => column_attributes(model))
end
{
models: model_t,
attributes: attributes_t
}
end
# Column translation
def column_attributes(model)
attrs = {}
ignored_columns = %w(id created_at updated_at)
(model.column_names - ignored_columns).map! do |col|
attrs.merge!(col => col.humanize.titleize)
end
attrs
end
# Model translation
def model_attributes(underscored)
name = underscored.humanize.titleize
{
underscored => {
'one' => name,
'other' => name.pluralize
}
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment