ruby-on-rails - 如何为去除文本数组的多个 Controller 编写方法?

标签 ruby-on-rails ruby string-substitution

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

@clear_company = clear_company(@company.name)

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

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

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

clean_array = %w[Inc. Incorporated LLC]

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

我该怎么做?

最佳答案

在 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

关于ruby-on-rails - 如何为去除文本数组的多个 Controller 编写方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3097629/

相关文章:

html - HTTP:如何在提交响应的同时检索下一个表单?

ruby-on-rails - 为什么只有某些调用会使用 devise_token_auth 使 token 失效/替换

vba - 用 Excel VBA 中的函数替换单元格区域

bash - 将 basename 的输出管道化为字符串替换

ruby - 数组方程解释

regex - R-从电话号码栏中删除破折号

ruby-on-rails - 在 rails 中以登录用户身份进行测试

ruby-on-rails - Rails 3.1 是否像支持条件 GET 一样支持条件 PUT?

ruby - 有没有一种简单的方法可以让 Mechanize 获取网页的所有组件?

ruby-on-rails - 为 delayed_job 设置 MAX_RUN_TIME - 我可以设置多少时间?