Question

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?

Was it helpful?

Solution

in 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

in config/initializers/string.rb:

class String
  include ClearCompany
end

if you like 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

OTHER TIPS

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

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

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

private
  def clean_name
    self.name = name.gsub(/Corporation|LLC|Incorporated|Inc.?/i, "").strip
  end 
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top