Skip to content

Commit

Permalink
Refactor LocaleAccessors
Browse files Browse the repository at this point in the history
  • Loading branch information
shioyama committed Jul 29, 2017
1 parent cd6a1fe commit a3658ea
Showing 1 changed file with 26 additions and 18 deletions.
44 changes: 26 additions & 18 deletions lib/mobility/locale_accessors.rb
Original file line number Diff line number Diff line change
Expand Up @@ -41,28 +41,36 @@ def self.apply(attributes, option)
# @param [String] One or more attribute names
# @param [Array<Symbol>] Locales
def initialize(*attribute_names, locales: I18n.available_locales)
warning_message = "locale passed as option to locale accessor will be ignored".freeze

attribute_names.each do |name|
locales.each do |locale|
normalized_locale = Mobility.normalize_locale(locale)
define_method "#{name}_#{normalized_locale}" do |**options|
return super() if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send(name, options) }
end
define_method "#{name}_#{normalized_locale}?" do |**options|
return super() if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send("#{name}?", options) }
end
define_method "#{name}_#{normalized_locale}=" do |value, **options|
return super(value) if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send("#{name}=", value, options) }
end
define_accessor(name, locale)
end
end
end

private

def define_accessor(name, locale)
warning_message = "locale passed as option to locale accessor will be ignored".freeze
normalized_locale = Mobility.normalize_locale(locale)

define_method "#{name}_#{normalized_locale}" do |**options|
return super() if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send(name, options) }
end

define_method "#{name}_#{normalized_locale}?" do |**options|
return super() if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send("#{name}?", options) }
end

define_method "#{name}_#{normalized_locale}=" do |value, **options|
return super(value) if options.delete(:super)
warn warning_message if options.delete(:locale)
Mobility.with_locale(locale) { send("#{name}=", value, options) }
end
end
end
end

0 comments on commit a3658ea

Please sign in to comment.