Calling a Module Method for a Specific Class

时间:2017-11-08 22:06:28

标签: ruby class module

If I have two classes that both include the same module but want a module method to be called only when one of the classes is saved how would I do this?

    module MusicMaker
      def good_music
        puts "this music rocks"
      end
    end

    class Jazz
      include MusicMaker
    end

    class ClassicRock
      include MusicMaker
    end

So I want both classes to include the MusicMaker module but want the good_music method to be called only when ClassicRock is saved and not when Jazz is saved. I want to do this inside the MusicMaker module and not in the classes.

2 个答案:

答案 0 :(得分:0)

假设您的模块定义了save方法,并且您希望它根据调用的类来表现不同。您可以在其中添加条件并检查self.class

的值
module MusicMaker
  def save
    case self.class
    when Jazz
      puts "jazz saved"
    when ClassicRock
      puts "classic rock saved"
    end
  end
end

Jazz.new.save # => "jazz saved"
ClassicRock.new.save # => "classic rock saved"

这类问题就是为什么在这种情况下你会使用模块而不是为每个类定义一个不同的save方法,如下所示:

class Jazz
  def save
    puts "jazz saved"
  end
end

class ClassicRock
  def save
    puts "classic rock saved"
  end
end

答案 1 :(得分:0)

如果您使用的是activerecord,我相信您可以使用class ClassicRock < ApplicationRecord include MusicMaker before_save :good_music end 课程中的document.style.backgroundColor = 'lightgrey'; 方法。就像

document.body.style.backgroundColor = "lightgrey";
相关问题