class ActiveModel::Name
def _singularize(string)
def _singularize(string) ActiveSupport::Inflector.underscore(string).tr("/", "_") end
def human(options = {})
BlogPost.model_name.human # => "Blog post"
end
extend ActiveModel::Naming
class BlogPost
it will underscore then humanize the class name.
Transform the model name into a more human format, using I18n. By default,
def human(options = {}) return @human if i18n_keys.empty? || i18n_scope.empty? key, *defaults = i18n_keys defaults << options[:default] if options[:default] defaults << MISSING_TRANSLATION translation = I18n.translate(key, scope: i18n_scope, count: 1, **options, default: defaults) translation = @human if translation == MISSING_TRANSLATION translation end
def i18n_keys
def i18n_keys @i18n_keys ||= if @klass.respond_to?(:lookup_ancestors) @klass.lookup_ancestors.map { |klass| klass.model_name.i18n_key } else [] end end
def i18n_scope
def i18n_scope @i18n_scope ||= @klass.respond_to?(:i18n_scope) ? [@klass.i18n_scope, :models] : [] end
def initialize(klass, namespace = nil, name = nil, locale = :en)
ActiveModel::Name.new(Foo::Bar).to_s
end
end
class Bar
module Foo
Use +locale+ argument for singularize and pluralize model name.
respectively.
and +name+ option will take the namespace and name of the given class
Returns a new ActiveModel::Name instance. By default, the +namespace+
def initialize(klass, namespace = nil, name = nil, locale = :en) @name = name || klass.name raise ArgumentError, "Class name cannot be blank. You need to supply a name argument when anonymous class given" if @name.blank? @unnamespaced = @name.delete_prefix("#{namespace.name}::") if namespace @klass = klass @singular = _singularize(@name) @plural = ActiveSupport::Inflector.pluralize(@singular, locale) @uncountable = @plural == @singular @element = ActiveSupport::Inflector.underscore(ActiveSupport::Inflector.demodulize(@name)) @human = ActiveSupport::Inflector.humanize(@element) @collection = ActiveSupport::Inflector.tableize(@name) @param_key = (namespace ? _singularize(@unnamespaced) : @singular) @i18n_key = @name.underscore.to_sym @route_key = (namespace ? ActiveSupport::Inflector.pluralize(@param_key, locale) : @plural.dup) @singular_route_key = ActiveSupport::Inflector.singularize(@route_key, locale) @route_key << "_index" if @uncountable end
def uncountable?
def uncountable? @uncountable end