如何为多个控制器编写一个去除文本数组的方法?
我想编写一种简化公司名称的方法。我希望它按如下方式工作:
@clear_company = clear_company(@company.name)
会发生@company.name =“Company, Inc.” @clear_company 将是“Company”
如果@company.name =“Company Corporation” @clear_company 将是“Company”
不会有多余的空格。我查看了不同的 strip 和 gsub,但我需要维护一个数组:
clean_array = %w[Inc. Incorporated LLC]
我可以更新它以使其更有效。
我该怎么做?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在 lib/clear_company.rb 中:
在 config/initializers/string.rb 中:
如果您喜欢 RSpec:
in lib/clear_company.rb:
in config/initializers/string.rb:
if you like RSpec:
末尾的
.strip
很重要,因为没有它,“X Inc.”将变成“X”。The
.strip
at the end is important because without it, "X Inc." would become "X ".清理数据并不是控制器真正关心的问题,因此最好将其保留在模型中。最简单的方法是使用
before_save
过滤器: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: