2

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

@clear_company = clear_company(@company.name)

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

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

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

clean_array = %w[Inc. Incorporated LLC]

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

我该怎么做?

4

3 回答 3

2

在 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
于 2010-06-23T00:55:52.950 回答
0
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”。

于 2010-06-22T22:37:05.367 回答
0

清理数据并不是控制器真正关心的问题,因此最好将其保留在模型中。最简单的方法是使用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
于 2010-06-23T01:55:21.457 回答