[英]Rails4 Application Model
i have the following function that i make use of in a lot of my models. 我在许多模型中都使用以下功能。 i use MongoID for MongoDB wrapper 我将MongoID用于MongoDB包装器
def make_slug
self.slug = self.name.downcase.gsub(/[^a-z1-9]+/, '').chomp('')
end
Which is the best place to place it than copy and paste it in all my models. 比将其复制并粘贴到所有模型中,这是放置它的最佳位置。
Also any recommendation for a good Slug Gem for Rails4? 另外,对于Rails4的优质子弹宝石有什么建议吗?
All models are Inherited from ActiveRecord, you can open the eigenclass to add a singleton method there and use in all models. 所有模型都继承自ActiveRecord,您可以打开eigenclass在此处添加单例方法并在所有模型中使用。
The method I'll choose would be putting it under lib directory and require it in each model I need it. 我选择的方法是将其放在lib目录下,并在需要的每个模型中都需要它。
I guess you could do a mixin/module, which you include in your models where you need the functionality. 我想您可以做一个mixin /模块,将其包含在模型中需要功能的位置。 Like this: 像这样:
Example of the module: 模块示例:
module SlugMaker
def make_slug
# Do your magic here
end
end
And then include it in your model: 然后将其包含在模型中:
class SuperAwesomeModel
include SlugMaker
def some_action
make_slug
end
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.