【问题标题】:Mixin a method to an existing module将方法混合到现有模块
【发布时间】:2013-06-27 15:44:33
【问题描述】:

我正在为 Rails 使用 linkedin 模块。我想在这个模块中向LinkedIn::Mash 类添加一个方法。我确实将mash.rb 文件添加到/models/concerns(我使用的是Rails 4):

module LinkedIn
    class Mash
        def my_method
        end
    end
end

但是,这不起作用:

my_mash_ojbect.respond_to? :my_method #=> false

我该如何解决这个问题?

【问题讨论】:

    标签: ruby-on-rails gem mixins


    【解决方案1】:

    试试

    LinkedIn::Mash.instance_eval do
      def my_method
      end
    end
    

    如果您想了解有关 instance_eval 的更多信息或阅读元编程 ruby​​ 书,请查看 this

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-02
      • 1970-01-01
      • 2021-04-03
      • 2012-10-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多