Take the 2-minute tour ×

I want to write a method that simplifies the names of corporations. I would like it to work as follows:

@clear_company = clear_company(@company.name)

What would happen is @company.name = "Company, Inc." @clear_company would be "Company"

If @company.name = "Company Corporation" @clear_company would be "Company"

There wouldn't be extra spaces. I looked at different strip and gsub, but I need to maintain an array:

clean_array = %w[Inc. Incorporated LLC]

I could update that to make it more effective.

How would I do this?

share|improve this question
add comment

3 Answers

up vote 2 down vote accepted

in lib/clear_company.rb:

 module ClearCompany
  BUSINESS_ENTITY = %w[Corporation Inc. Incorporated LLC]

  def clear_company

  def strip_business_entity
    BUSINESS_ENTITY.inject(self) do |company, clean_word|
      company.sub(clean_word, '')

  def remove_trailing_punctuation
    strip.sub(/,$/, '')

in config/initializers/string.rb:

class String
  include ClearCompany

if you like RSpec:

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

  it "removes ' Corporation' from the end" do
    "Company Corporation".clear_company.should == "Company"
share|improve this answer
yeah I would have extended String as well –  Mike Jun 23 '10 at 10:14
where do I extend the String class? do I put in config/initializers/clear_company.rb file? –  Angela Jun 23 '10 at 22:43
I'd extract the behavior above into lib/clear_company.rb as a module and then monkey patch String in config/initializers/string.rb to simply include ClearCompany –  Bryan Ash Jun 24 '10 at 1:04
I see...so the code in clear_company.rb in the /lib would still be the same as above, and then I apply the patch to string.rb? –  Angela Jun 25 '10 at 4:34
hi so would I still use it as described clear_company(company.name) or is it company.name.clear_company? –  Angela Jul 28 '10 at 3:03
show 2 more comments
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

The .strip at the end is important because without it, "X Inc." would become "X ".

share|improve this answer
add comment

Cleaning data is not really a concern of the controller, so its best keep it in the model. The easiest way is using a before_save filter:

class Company < ActiveRecord::Base
  before_save :clean_name

  def clean_name
    self.name = name.gsub(/Corporation|LLC|Incorporated|Inc.?/i, "").strip
share|improve this answer
add comment

Your Answer


