代码之家  ›  专栏  ›  技术社区  ›  Peter

重载ActiveSupport的默认to_sentence行为

  •  2
  • Peter  · 技术社区  · 16 年前

    to_sentence

    require 'active_support'
    [1,2,3].to_sentence  # gives "1, 2, and 3"
    [1,2,3].to_sentence(:last_word_connector => ' and ')  # gives "1, 2 and 3"
    

    你可以更改最后一个单词的连接器,这很好,因为我不想有额外的逗号。但它需要额外的文本:44个字符而不是11个!

    问题 :更改默认值的最像ruby的方法是什么 :last_word_connector ' and '

    3 回复  |  直到 15 年前
        1
  •  12
  •   Community Mohan Dere    5 年前

    好吧,它是可本地化的,所以你可以 specify a default 'en'和'for的值 support.array.last_word_connector

    请参阅:

    发件人:conversion.rb

    def to_sentence(options = {})
    ...
       default_last_word_connector = I18n.translate(:'support.array.last_word_connector', :locale => options[:locale])
    ...
    end
    

    rails i18n

    en:
      support:
        array:
          last_word_connector: " and "
    

     
    Loading development environment (Rails 2.3.3)
    >> [1,2,3].to_sentence
    => "1, 2 and 3"
    
        2
  •  -1
  •   Martin DeMello    16 年前

    here 提供了一种很好的方法。它不会遇到与别名技术相同的问题,因为没有遗留的“旧”方法。

    以下是如何将该技术用于您的原始问题(用ruby 1.9测试)

    class Array
      old_to_sentence = instance_method(:to_sentence)
      define_method(:to_sentence) { |options = {}|
    
        options[:last_word_connector] ||= " and "
        old_to_sentence.bind(self).call(options)
      }
    end
    

    您可能还想阅读 UnboundMethod

        3
  •  -1
  •   David Miani    16 年前
     class Array
       alias_method :old_to_sentence, :to_sentence
       def to_sentence(args={})
         a = {:last_word_connector => ' and '}
         a.update(args) if args
         old_to_sentence(a)
       end
     end