Florian Gilcher
5/16/2008 7:37:00 PM
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On May 16, 2008, at 8:55 PM, Adrian wrote:
> Hi
>
> This maybe a pretty obvious question - but I decided to ask anyway.
>
> I am trying to class a method defined within an included module from a
> class level method as below.
>
> Is there a better way to do this? (Assumming that the class level
> method cannot be changed to a instance method.)
>
> class Report
> include FormatHelper
>
> self.generate_report
> ...
> my_date = self.format_date(...)
> ...
> end
> end
>
> module FormatHelper
>
> self.format_date(date)
> ...
> end
> end
>
> Any help welcome
>
> Cheers
> Adrian
>
Hi,
Class Methods of Modules are local to the module.
If you want to extend a Class by the instance Methods of a Module, you
have to possibilities:
Use "extend" instead of "include":
module A
def foo
"foo"
end
end
class C
extend A
def self.bar
foo
end
end
include the Methods within the "metaclass":
class D
class << self
include A
end
def self.bar
foo
end
end
If you wish to keep class an instance methods separated, it is
somewhat popular
to define them in different modules:
module FormatHelper
module ClassMethods
def foo
#####
end
#some more methods
end
module InstanceMethods
def foo
#####
end
#some more methods
end
end
class D
include FormatHelper::InstanceMethods
extend FormatHelper::ClassMethods
end
Have a lot of fun.
Florian Gilcher
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.8 (Darwin)
iEYEARECAAYFAkgt4kgACgkQJA/zY0IIRZahUACfSmUEdASjoZ+6DvQO372+VrHN
27UAnRraICcKvGegxzRb5xWeqargnoKs
=zIpa
-----END PGP SIGNATURE-----