简体   繁体   English

Rails助手方法

[英]Rails helper methods

I'm doing some refactoring on a piece of code I have, and am thinking of moving some stuff from the model into helper methods. 我正在对我拥有的一段代码进行一些重构 ,并且正在考虑将某些东西从模型移到辅助方法中。

Nothing major, but my model does some screen-scraping, and I need to treat (and filter) some of the strings returned, so they are passed back to the controller nicely formatted. 没什么大不了的,但是我的模型做了一些屏幕刮擦,我需要处理(并过滤)一些返回的字符串,因此它们会以良好的格式传递回控制器。

I've been using helper methods with my view already. 我已经在视图中使用辅助方法。

My question is, is it a good practice to use helper methods with the model, or should I simply add my string cleaning methods in the model itself? 我的问题是,在模型中使用辅助方法是一种好习惯,还是我应该在模型本身中简单地添加字符串清洗方法?

Thanks in advance 提前致谢

Since you don't give an example, it's hard to be specific, but in general, I like to put re-usable functionality in models, especially if it relates to the model in question. 由于您没有给出示例,因此很难具体说明,但是总的来说,我喜欢在模型中放置可重用功能, 尤其是当它与所讨论的模型有关时。

A generic example off the top of my head: 一个普通的例子浮现在脑海:

def name
  first_name + " " + last_name
end

Instead of having the equivalent in a helper method. 而不是在助手方法中使用等效方法。 I mean, if you already have a model dedicated to screen-scraping, it makes sense that it would have a bunch of methods in it (maybe extracted into modules/libraries/plugins where appropriate) that did the business involved in screen scraping. 我的意思是,如果您已经拥有专用于屏幕抓取的模型,那么它中将包含一堆从事屏幕抓取业务的方法(可能会提取到模块/库/插件中)是有意义的。

I have seen examples of people using helper methods with models, but I try to avoid that in general. 我看到了一些人们在模型中使用辅助方法的例子,但我通常会尽量避免这种情况。 That said, there are exceptions to every rule. 也就是说,每条规则都有例外。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM