如何覆盖DeviseController#find_message?

时间:2017-06-22 10:56:05

标签: ruby-on-rails devise internationalization

我需要在我的视图中手动进行I18n翻译以支持并行翻译多种语言,但Devise会根据当前语言环境在内部翻译它的flash消息,并在{中设置结果字符串{1}}。

我需要将I18n键和选项添加到#import <Foundation/Foundation.h> typedef id (^ReduceBlock)(id accumulator,id item); @interface NSArray (HigherOrderFunctions) -(id)reduce:(id)initial combine:(ReduceBlock)combine; @end #import "NSArray+HigherOrderFunctions.h" @implementation NSArray (HigherOrderFunctions) -(id)reduce:(id)initial combine:(ReduceBlock)combine{ id accumulator = initial; for (id item in self) { accumulator = combine(accumulator, item); } return accumulator; } @end ,以便我可以执行类似

的操作
   NSArray *numbers = @[@5,@7,@3,@8];
    NSNumber *sum = [numbers reduce:@0 combine:^id(id accumulator, id item) {
        return @([item intValue] + [accumulator intValue]);
    }];
    NSNumber *multiplier = [numbers reduce:@1 combine:^id(id accumulator, id item) {
        return @([item intValue] * [accumulator intValue]);
    }];
    NSLog(@"sum=%@,multiplier=%@",sum,multiplier);

看起来有问题的代码是DeviseController#find_message,但我无法弄清楚如何覆盖/猴子补丁......我已经尝试了

flash
flash中的

,但似乎没有效果。

如何覆盖或修补此行为?

顺便说一下,我使用Devise 4.3.0(编写本文时最近)和Rails 5.1.1。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我明白了;对于其他任何人:你想要覆盖Devise::FailureApp#i18n_message

这有效:

Devise::FailureApp.class_eval do
  protected
    def i18n_message(default = nil)
      message = warden_message || default || :unauthenticated

      if message.is_a?(Symbol)
        options = {}
        options[:resource_name] = scope
        options[:scope] = "devise.failure"
        options[:default] = [message]
        auth_keys = scope_class.authentication_keys
        keys = (auth_keys.respond_to?(:keys) ? auth_keys.keys : auth_keys).map { |key| scope_class.human_attribute_name(key) }
        options[:authentication_keys] = keys.join(I18n.translate(:"support.array.words_connector"))
        options = i18n_options(options)

        # I18n.t(:"#{scope}.#{message}", options)
        {key: :"#{scope}.#{message}", options: options}
      else
        message.to_s
      end
    end
end