Created
July 10, 2015 18:53
-
-
Save buren/56912b4ee6d7e1d6aea7 to your computer and use it in GitHub Desktop.
Generate translations for activerecord models and columns
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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