2

企業名を簡略化する方法を書きたい。私はそれが次のように機能することを望みます:

@clear_company = clear_company(@company.name)

何が起こるかは@company.name= "Company、Inc."です。@clear_companyは「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

データのクリーニングは実際にはコントローラーの関心事ではないため、モデルに保持するのが最善です。最も簡単な方法は、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 に答える
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がなければ「XInc.」なので、最後のは重要です。「X」になります。

于 2010-06-22T22:37:05.367 に答える