Ruby类函数定义的几种方式
参考:
ruby-defining-class-methods
1、
1. class
2. def
3. ...
4. end
5. end
这种方式,有一点不好,如果更改类名,相应的类函数定义的类名也要更改。
2、
1. class
2. def self.find(id)
3. ...
4. end
5. end
这种方式比较好,没有上面提到的问题。作者也推荐使用这种方式。
3、
1. class
2. class << self
3. protected
4. def
5. ...
6. end
7. end
8. end
在定义protected类函数时使用。为什么要定义protected类函数可参见作者的另一篇文章
4、比较复杂的
1. class Object # http://whytheluckystiff.net/articles/seeingMetaclassesClearly.html
2. def
3. class << self; self; end).instance_eval { define_method
4. end
5. end
6.
7. class
8. def self.responses(hash)
9. each do
10. do
11. result
12. end
13. end
14. end
15.
16. :success => 20, :unreachable
17. end
18.
19. Service.success # => 20
20. Service.unreachable # => 23
由于本人Ruby功力还不够,上面的代码有些还看不明,有兴趣的读者可直接看原文。
5、最后作者还提到一种方式
1. class
2. do
3. def
4. ...
5. end
6. end
7. end
用到instance_eval,没搞清楚这种方式有什么特点。