How to get context call object in Ruby?

it will continue to be my part of the code, which I want to simplify in order to avoid passing an additional argument for each call. Actually, my usecase is what Mis a user library without defining an argument contextfor each method. checkis a method that is not defined by the user.

# User code
module M
  def do_something(context)
    puts "Called from #{context}"
    context.check
  end
  module_function :do_something
end

# Application code
class Bar
  def check
    puts "Checking from #{self}..."
  end
end

class Foo < Bar
  def do_stuff(scope, method)
    scope.send method, self
  end
end

# Executed by user
Foo.new.do_stuff M, :do_something

Is there a way to do the same without passing selfas an input argument to the method do_somethingto retrieve the method check?

# User code
module M
  def do_something
    called_from_object = ???
    puts "Called from #{called_from_object}"
    called_from_object.check
  end
  module_function :do_something
end

# Application code
class Bar
  def check
    puts "Checking from #{self}..."
  end
end

class Foo < Bar
  def do_stuff(scope, method)
    scope.send methood
  end
end

# Executed by user
Foo.new.do_stuff M, :do_something

Thanks for your support!

+3
source share
2 answers

Found this post, looking for an answer for my own purposes.

, Ruby . - - , Ruby 1.9.1:

sudo gem install

Ruby 1.8, 1.8 .

http://rubygems.org/gems/sender

+5

, , Foo M, , ? .

module M
  def do_something
    puts "I am going to use the test method from the including class"
    test
  end
end

class Foo
  include M
  def test
    puts "In Foo test method"
  end

  def do_stuff
    do_something
  end
end

:

irb(main):019:0> Foo.new.do_stuff
I am going to use the test method from the including class
In Foo test method

, , , , . Comparable, , <=>.

+1

Source: https://habr.com/ru/post/1740593/


All Articles