Vincent
Vincent

Reputation: 16226

Calling module class methods without module name in Ruby

Is it possible to substitute

@m1 = MyModule.method1
@m2 = MyModule.method2
@m3 = MyModule.method3
@m4 = MyModule.method4

with something like this

with MyModule do

  @m1 = method1
  @m2 = method2
  @m3 = method3
  @m4 = method4

end

in Ruby?

Upvotes: 1

Views: 288

Answers (2)

Jörg W Mittag
Jörg W Mittag

Reputation: 369614

No, this is not possible. Method calls without an explicit receiver have an implicit receiver of self, so in order to make method1 a call to MyModule.method1, self needs to be changed to MyModule. That's easy enough, after all, that's what instance_eval and instance_exec are for.

However, instance variables also belong to self, that's why they are called instance variables, after all. So, if you change self to MyModule, then @m1, @m2 etc. will also belong to MyModule and no longer to whatever object they belong to in your code example.

In other words, you need self to change but you also need self not to change. That's a contradiction, ergo, what you want isn't possible.

Upvotes: 1

Zach Kemp
Zach Kemp

Reputation: 11904

You could do something like this:

def with(context, &block)
  yield context
end

with MyModule do |m|
  @m1 = m.method1
  @m2 = m.method2
  ...
end

I'm not totally sure what benefit this gives you - could you be more specific about how you plan to use this?

Upvotes: 2

Related Questions