lib/olson/class_methods.rb in olson-0.0.2 vs lib/olson/class_methods.rb in olson-0.0.3

- old
+ new

@@ -28,17 +28,20 @@ end # end attr_options = :"#{ attr }_options" define_singleton_method attr_options do # def status_options options_for_select_with_i18n attr, # options_for_select_with_i18n 'status', - model_class.send(attr_options) # User.status_options + source_class.send(attr_options) # User.status_options end # end end end # Humanize an attribute using I18n, falling back to the humanized attributes value. # + # The `.default_humanize` method can be overridden to configure how values are humanized + # when they are not found in I18n. + # # I tend to store attributes like `status` or `role` as underscored strings (a string that # would be suitable for a method/variable name) sometimes a simple .humanize will do the # trick when it comes to displaying that value in the UI user but other times you need to # customize them a bit which is one reason I18n is great. This helps automate the usage of # I18n for such a purpose. @@ -71,14 +74,31 @@ # # @user.plan_status = 'active' # @user.decorator.plan_status # => 'Current' # # @user.activation_status = 'inactive' - # @user.decorator.activation_status = 'Inactive' - def humanize(attribute, key, default = key.to_s.humanize) - i18n_with_scoped_defaults key, [model_name.i18n_key, attribute], default if key.present? + # @user.decorator.activation_status # => 'Inactive' + def humanize(attribute, value, default = default_humanize(value)) + i18n_with_scoped_defaults value, [model_name.i18n_key, attribute], default if value.present? end + # The default way to humanize a value when not found in I18n. + # + # To configure the default humanization, you can override `.default_humanize` in your + # decorator. For example, to use `String#titleize` instead of `String#humanize`: + # + # # user_decorator.rb + # class UserDecorator < ApplicationDecorator + # decorates :user + # + # def self.default_humanize(value) + # value.to_s.titleize + # end + # end + # + def default_humanize(value) + value.to_s.humanize + end # Try to translate a key with I18n and a scope but fallback to less-and-less scope. # An example will explain more clearly: # # i18n_with_scoped_defaults(:some_key, [:foo, :bar, :baz])