【问题标题】:How do I write a method for multiple controllers that strips out an array of text?如何为多个控制器编写一个去除文本数组的方法?
【发布时间】:2010-06-22 22:29:38
【问题描述】:

我想写一个简化公司名称的方法。我希望它按如下方式工作:

@clear_company = clear_company(@company.name)

会发生什么是@company.name = "Company, Inc." @clear_company 将是“公司”

如果@company.name = "Company Corporation" @clear_company 将是 "Company"

不会有多余的空格。我看了不同的strip和gsub,但我需要维护一个数组:

clean_array = %w[Inc. Incorporated LLC]

我可以更新它以使其更有效。

我该怎么做?

【问题讨论】:

    标签: ruby-on-rails ruby string-substitution


    【解决方案1】:

    在 lib/clear_company.rb 中:

     module ClearCompany
      BUSINESS_ENTITY = %w[Corporation Inc. Incorporated LLC]
    
      def clear_company
        strip_business_entity.remove_trailing_punctuation
      end
    
      def strip_business_entity
        BUSINESS_ENTITY.inject(self) do |company, clean_word|
          company.sub(clean_word, '')
        end
      end
    
      def remove_trailing_punctuation
        strip.sub(/,$/, '')
      end
    end
    

    在 config/initializers/string.rb:

    class String
      include ClearCompany
    end
    

    如果你喜欢 RSpec:

    describe String, :clear_company do
      it "removes ', Inc.' from the end" do
        "Company, Inc.".clear_company.should == "Company"
      end
    
      it "removes ' Corporation' from the end" do
        "Company Corporation".clear_company.should == "Company"
      end
    end
    

    【讨论】:

    • 是的,我也会扩展字符串
    • 我在哪里扩展 String 类?我应该放入 config/initializers/clear_company.rb 文件吗?
    • 我会将上面的行为作为一个模块提取到lib/clear_company.rb 中,然后将config/initializers/string.rb 中的字符串修改为简单的include ClearCompany
    • 我明白了...所以 /lib 中 clear_company.rb 中的代码仍然与上面相同,然后我将补丁应用于 string.rb?
    • 嗨,我还是会按照 clear_company(company.name) 的描述使用它还是 company.name.clear_company?
    【解决方案2】:
    def clear_company(name)
      clean_array = %w[Inc. Incorporated LLC]
      name = name.strip
      word_to_remove = clean_array.find {|x| name[/#{x}$/] }
      name.sub(/#{word_to_remove}$/, '').strip
    end
    

    最后的.strip 很重要,因为没有它,“X Inc.”会变成“X”。

    【讨论】:

      【解决方案3】:

      清理数据并不是控制器真正关心的问题,因此最好将其保留在模型中。最简单的方法是使用before_save 过滤器:

      class Company < ActiveRecord::Base
        before_save :clean_name
      
      private
        def clean_name
          self.name = name.gsub(/Corporation|LLC|Incorporated|Inc.?/i, "").strip
        end 
      end
      

      【讨论】:

        猜你喜欢
        • 2014-11-23
        • 1970-01-01
        • 1970-01-01
        • 2020-12-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多