[英]Rails ActiveSuppport:Concern and Private Methods
This is a great idea about concern in rails: http://37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns 关于rails的关注点是个好主意:http: //37signals.com/svn/posts/3372-put-chubby-models-on-a-diet-with-concerns
And it's also a good idea to make very small methods that are not part of a public API. 并且制作非常小的方法也是一个好主意,这些方法不属于公共API。 Without using concerns, those become private methods in a ruby class.
没有使用顾虑,那些成为ruby类中的私有方法。
Does it makes sense to create private methods inside of a Rails ActiveSupport::Concern module? 在Rails ActiveSupport :: Concern模块中创建私有方法是否有意义? If so, does private work both for regular instance methods and class methods in the concern definition?
如果是这样,私有工作是否在关注定义中用于常规实例方法和类方法?
Does it makes sense to create private methods inside of a Rails
ActiveSupport::Concern
module?在Rails
ActiveSupport::Concern
模块中创建私有方法是否有意义?
Considering that concerns are smart modules that will eventually be included in other classes — yes, it does. 考虑到关注点是最终将被包含在其他类中的智能模块 - 是的,确实如此。 It's just a portable code, extractable behavior and I'd like to consider it as part of my controller (or model, etc.) as I'm writing it.
它只是一个可移植的代码,可提取的行为,我想把它当作我的控制器(或模型等)的一部分,因为我正在编写它。 So basically you just declare methods
private
or protected
as you normally would. 所以基本上你只是像往常一样声明方法
private
或protected
。
Maybe the post you linked have been updated since 2013, but DHH does exactly that in the one of the examples there: 也许您链接的帖子自2013年以来已更新,但DHH在其中一个示例中完成了这一点:
module Dropboxed
extend ActiveSupport::Concern
included do
before_create :generate_dropbox_key
end
def rekey_dropbox
generate_dropbox_key
save!
end
private # <- Let's list some privates
def generate_dropbox_key
self.dropbox_key = SignalId::Token.unique(24) do |key|
self.class.find_by_dropbox_key(key)
end
end
end
As to private
class methods, I agree with @Hugo and never used them myself, but here's how you can achieve this: 至于
private
类方法,我同意@Hugo并且从未使用过它们,但是这里是你如何实现这个目标:
module Dropboxed
extend ActiveSupport::Concern
included do
private_class_method :method_name
end
module ClassMethods
def method_name
end
end
end
It's just my opinion but right now I'm scratching my head about private class method, what are they good for? 这只是我的意见,但现在我对私人班级方法感到头疼,他们有什么好处? Anyway, if you really need them refer to this post: How to create a private class method?
无论如何,如果你真的需要它们,请参考这篇文章: 如何创建一个私有类方法?
It does make sense to have private instance methods in a concern module and will work fine. 在关注模块中使用私有实例方法确实有意义,并且可以正常工作。 Private class methods will work fine as well but following the above stated post.
私人类方法也可以正常工作,但遵循上述帖子。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.