Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using define_method inside a Module that gets included inside a Class?

I got something like this:

module MyModule
    define_method(:foo){ puts "yeah!" }
end

class User
  include MyModule
end

But this does not work as intended... They are not defined. Also I need to use the Module because I want to distinguish the Methods from there from the normal User Methods. Which I do like this:

MyModule.instance_methods

Please help .. what am I missing? I also tried:

module MyModule
  (class << self; self; end).class_eval do
    define_method(:foo){ puts "yeah!" }
  end
end

which also doesn't work :/

to clarify ... I would like to use:

User.first.foo

not

MyModule.foo
like image 276
nex Avatar asked Aug 25 '11 16:08

nex


2 Answers

You can always use the extend self trick:

module MyModule
  define_method(:foo){ puts "yeah!" }

  extend self
end

This has the effect of making this module both a mixin and a singleton.

like image 94
tadman Avatar answered Nov 04 '22 01:11

tadman


If you want to have a class method the following will work

module MyModule
    define_singleton_method(:foo){ puts "yeah!" }
end

MyModule.foo
# >> yeah!
like image 28
James Kyburz Avatar answered Nov 04 '22 01:11

James Kyburz