[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.ruby

modules and class methods.

Brad Phelan

5/4/2007 1:56:00 PM

Why does this not work!

########################################
module Foo
def self.foo a
puts a
end
end

class Bar
include Foo
foo "hello"
end

foo.rb:20: undefined method `foo' for Bar:Class (NoMethodError)
####################################

but this does

class Bar
def self.foo a
puts a
end
foo "hello"
end



What am I misunderstanding about modules????

--
Brad
http://xt...
3 Answers

Brad Phelan

5/4/2007 2:33:00 PM

0

Brad Phelan wrote:
> Why does this not work!
>
> ########################################
> module Foo
> def self.foo a
> puts a
> end
> end
>
> class Bar
> include Foo
> foo "hello"
> end
>
> foo.rb:20: undefined method `foo' for Bar:Class (NoMethodError)
> ####################################
>
> but this does
>
> class Bar
> def self.foo a
> puts a
> end
> foo "hello"
> end
>
>
>
> What am I misunderstanding about modules????
>
> --
> Brad
> http://xt...

The below code obviously work the way I wish

module Foo
def foo
puts "a"
end
end

class Bar
extend Foo
puts foo
end

however is there any way to get the same effect by using include. I
would like to mix in class and instance methods in one call. It seems
I can do one or the other but not both at the same time. Is that
correct?

--
Brad Phelan
http://xt...

dblack

5/4/2007 9:48:00 PM

0

Brad Phelan

5/7/2007 6:46:00 AM

0


>
> You can use the inherited hook in Module to do both -- for example:
>
> module M
> def self.included(c)
> m = self
> c.class_eval { extend m }
> end
>
> def meth
> puts "here"
> end
> end
>
> class C
> include M
> end
>
> C.meth # here
> C.new.meth # here
>
>
> David
>

Now that is the sneaky little hook I was looking for.

Thanks

Brad

--
http://xt...