On May 28, 2:59 am, Julian Leviston <[email protected]> wrote:
> Hi,
>
> >    def self.included(base)
> >      base.send :extend, ClassMethods
> >    end
>
> >    module ClassMethods
> >      def my_method
> >      end
> >    end
>
> This is not a class method, is it? it's an instance method. a class  
> method would be
>
> def self.my_method
> end
>
>

I have all of 20 hours of Ruby experience now, so I'll probably screw
up this explanation.  The whole include/extend thing is still very
confusing to me, but I'm having ActiveRecord::Base call include on my
module and attaching a callback so that I can do more.
ActiveRecord::Base is an instance of the Class class, so when the
callback uses extend, it is the ActiveRecord::Base instance itself
(and ActiveRecord::Base objects) that pick up the new my_method
instance method.  My understanding is that Ruby then attaches this to
a metaclass for the ActiveRecord::Base instance, making it a singleton
method.  And I think that's all class methods really are; singleton
methods on the metadata class for an instance of the Class class.  So
through module trickery I have created a new class method.

If I have this wrong, let me know.  I don't like to write code that I
don't understand, so the sooner I wrap my head around the actual
mechanics of how this works, the better.

>
> I don't follow what you want to do here... you're calling the method  
> inside the class definition. That makes no sense. What did you want to  
> happen?
> In other words, you're running a method WHILE declaring the class.
>

For any language other than ruby, I would agree that this doesn't make
sence.  :)

Apparently it's standard practice though for this language. You can
run methods right in the middle of your class definition.  You can try
this out pretty easily in irb:

  irb(main):001:0> class A
  irb(main):002:1> puts "hello!"
  irb(main):003:1> end
  hello!
  => nil

Strange!  But useful.  In my case I'm actually planning to create
three class methods similar to my_method above.  When run these will
generate instance methods for my models (similar to associations).
--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to