views:

71

answers:

3

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?

A: 
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 ".

Adrian
+2  A: 

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
Bryan Ash
yeah I would have extended String as well
Mike
where do I extend the String class? do I put in config/initializers/clear_company.rb file?
Angela
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
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
hi so would I still use it as described clear_company(company.name) or is it company.name.clear_company?
Angela
nevermind, I looked at rspec and got it going...thanks!
Angela
You see that the spec `"Company, Inc.".clear_company.should == "Company"` is an example of sending the message `clear_company` to a String and the expected outcome. I've introduced RSpec to a number of people, some get it immediately, but for others the language doesn't come right away. I get the impression that they expect the code to be less readable.
Bryan Ash
A: 

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