code_junkie

Difference between &ldquo;class << anObject&rdquo; and anObject.class_eval

Nov 12th, 2011
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.53 KB | None | 0 0
  1. module AttributeFu
  2. module Associations #:nodoc:
  3. def self.included(base) #:nodoc:
  4. base.class_eval do
  5. extend ClassMethods
  6. class << self; alias_method_chain :has_many, :association_option; end
  7.  
  8. class_inheritable_accessor :managed_association_attributes
  9. write_inheritable_attribute :managed_association_attributes, []
  10.  
  11. after_update :save_managed_associations
  12. end
  13. end
  14.  
  15. ...
  16. end
  17. end
  18.  
  19. class << self; alias_method_chain :has_many, :association_option; end
  20.  
  21. /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method': undefined method `has_many' for class `ActiveRecord::Base' (NameError)
  22. from /usr/lib/ruby/gems/1.8/gems/activesupport-2.1.1/lib/active_support/core_ext/module/aliasing.rb:31:in `alias_method_chain'
  23. from /home/twong/git/physpace/vendor/plugins/attribute_fu/lib/attribute_fu/associations.rb:9:in `included'
  24.  
  25. # init.rb
  26. ActiveRecord::Base.class_eval { include AttributeFu::Associations }
  27.  
  28. module AttributeFu
  29. module Associations
  30. def self.included(base)
  31. # base == ActiveRecord::Base (the class)
  32. base.class_eval do
  33. # class_eval makes self == ActiveRecord::Base, and makes def define instance methods.
  34. extend ClassMethods
  35.  
  36. # If has_many were an instance method, we could do this
  37. # alias_method_chain :has_many, :association_option; end
  38. # but it's a class method, so we have to do the alias_method_chain on
  39. # the meta-class for ActiveRecord::Base, which is what class << self does.
  40. class << self; alias_method_chain :has_many, :association_option; end
  41. end
  42. end
  43. end
  44. end
  45.  
  46. class A ; end
  47. A.class_eval { puts self.inspect ; class << self ; puts self.inspect ; end }
  48.  
  49. class << self
  50. ...
  51. end
  52.  
  53. SomeThing.bar_method
  54.  
  55. assoc = SomeThing.new
  56. assoc.foo_method
  57.  
  58. class SomeThing
  59. def foo_method
  60. ...
  61. end
  62. class << self
  63. def bar_method
  64. ...
  65. end
  66. end
  67. end
  68.  
  69. def self.has_many_with_association_options
  70. ...
  71. end
  72.  
  73. class << self
  74. def has_many_with_association_options
  75. ...
  76. end
  77. end
Add Comment
Please, Sign In to add comment