从类中调用包含模块的方法

时间:2016-04-27 22:13:24

标签: ruby-on-rails ruby inheritance module super

我有一个用例class A,其中包含module B

class A
  include B

  def do_one_thing
    # override module's method. do something different instead
  end

  def do_another_thing
    # Call `do_one_thing` from here,
    # but call the module's method, not the one I overrode above.
  end
end

module B
  included do
    def do_one_thing
      # ...
    end
  end

  # some other methods
end

如上所示,我从do_one_thing致电do_another_thing。我的问题是我需要调用模块的方法(即super方法)。这可能在Rails中吗?

2 个答案:

答案 0 :(得分:1)

要使用included方法使用B方法,您需要extend ActiveSupport::Concern模块module B def do_one_thing puts 'in module' # ... end # some other methods end class A include B def do_one_thing super puts 'in class' # override module's method. do something different instead end def do_another_thing do_one_thing # Call `do_one_thing` from here, # but call the module's method, not the one I overrode above. end end A.new.do_one_thing ,但这不会为您提供所需的行为。

如果我是你,我会放弃那种模式并使用简单的原生Ruby模块模式:

    public class VoiceUser extends Thread {                                     // CHAT USER
    private ObjectOutputStream clientOutput;

    public VoiceUser(Socket sv) {
        try {
            System.out.println("VSTART");
            clientOutput = new ObjectOutputStream(sv.getOutputStream());
            outputArray.add(clientOutput);
        } catch (IOException e) {
            System.out.println("Can't create stable connection between server and client");
        }
    }
    public void run() {
        try {
            AudioFormat af = new AudioFormat(8000.0f,8,1,true,false);
            DataLine.Info info = new DataLine.Info(TargetDataLine.class, af);
            TargetDataLine microphone = (TargetDataLine)AudioSystem.getLine(info);
            microphone.open(af);
            microphone.start();
            int bytesRead = 0;
            byte[] soundData = new byte[1];
            while(bytesRead != -1)
            {
                bytesRead = microphone.read(soundData, 0, soundData.length);
                System.out.println(soundData.length);
                if(bytesRead >= 0)
                {
                    for(ObjectOutputStream o : outputArray) {
                        o.write(soundData, 0, bytesRead);
                    }
                }
            }
        } catch (IOException | LineUnavailableException e) {
            e.printStackTrace();
        }
    }
}

上面的代码将正确使用您正在寻找的模块继承。

Read more about Ruby module inheritance here

答案 1 :(得分:0)

您可以在覆盖

之前“保存”包含的方法
module B
  extend ActiveSupport::Concern

  included do
    def do_one_thing
      puts 'do_one_thing'
    end
  end
end

class A
  include B

  alias_method :old_do_one_thing, :do_one_thing
  def do_one_thing
    puts "I'd rather do this"
  end

  def do_another_thing
    old_do_one_thing
  end
end

a= A.new
a.do_one_thing
a.do_another_thing