ruby - 如何从 Ruby 中的模块中混合一些类方法和一些实例方法?

标签 ruby mixins

我有一个模块,想混合一些方法作为类方法,一些方法作为实例方法。

例如:

module Foo
  def self.class_method
  end

  def instance_method
  end
end

class Bar
  include Foo
end

用法:

Bar.class_method
Bar.new.instance_method

在 Ruby 中可以这样做吗?

如果不是,是否可以在 Bar 类中定义哪些方法是类方法,哪些是实例方法?

希望将同一个方法同时定义为类方法和实例方法。

最佳答案

这种模式在 Ruby 中很常见。如此普遍,事实上,ActiveSupport::Concern对其进行了一些抽象。

您的典型实现如下所示:

module Foo
  def self.included(other_mod)
    other_mod.extend ClassMethods
  end

  def instance_method
  end

  module ClassMethods
    def class_method
    end
  end
end

class Bar
  include Foo
end

不幸的是,如果不以某种方式将包含的模块分成多个部分,您将无法像您描述的那样轻松完成此操作。

关于ruby - 如何从 Ruby 中的模块中混合一些类方法和一些实例方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21918056/

相关文章:

ruby-on-rails - Ruby on Rails 中的竞争条件

ruby-on-rails - 在 Rails 4 中接收 POST 数据并读取 request.body

ruby - sinatra 中的 Controller 是什么?

mysql - ld : library not found for -lzstd while bundle install for mysql2 gem Ruby on macOS Big Sur 11. 4

ruby - 在插值之前检索原始字符串

LESS 过渡混合

Javascript 混入

javascript - 如何使用带有链接支持的 lodash 和 typescript 的 mixins

twitter-bootstrap-3 - Bootstrap 3 mixin 多个 make-*-column

sass - 从混入中删除/移除属性