Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Do ruby modules have constructors?

Something that is called when it is extended.

Eg. this piece of code:

module M
  def init(x)
    @x = 5
    self
  end
  def foo
    super
    puts @x
  end
end
class D
  def foo
    puts 1
  end
end

D.new.extend(M).init(5).foo

works and returns 1 5. But I want to change the last line to read

D.new.extend(M.init(5)).foo

or better yet

D.new.extend(M(5)).foo

to prevent bugs from not setting @x.

On a similar note, can I say something like

class X
  include Debug(5)
like image 811
alexloh Avatar asked Jun 23 '26 12:06

alexloh


1 Answers

You can do that by having a method that returns a Module.

def M(par)
  m = Module.new
  m.module_eval %Q{
    def foo
      super
      puts #{par}
    end
  }
  m
end

D.new.extend(M(5)).foo # => 5

class X
  include M(4)
end

X.new.foo # => 4
like image 99
Jakub Hampl Avatar answered Jun 25 '26 01:06

Jakub Hampl



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!