加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 我可以使用Module#关于?定义类方法吗?

发布时间:2020-12-17 04:26:05 所属栏目:百科 来源:网络整理
导读:我想使用Module#related( https://github.com/37signals/concerning – Rails 4.1的一部分)来定义类方法.这样我就可以将单个类使用的模块移回到类中. 但是,似乎我无法定义类方法.鉴于这种: class User ActiveRecord::Base attr_accessible :name concerning
我想使用Module#related( https://github.com/37signals/concerning – Rails 4.1的一部分)来定义类方法.这样我就可以将单个类使用的模块移回到类中.

但是,似乎我无法定义类方法.鉴于这种:

class User < ActiveRecord::Base
  attr_accessible :name

  concerning :Programmers do
    module ClassMethods 
      def programmer?
        true
      end
    end
  end

  module Managers 
    extend ActiveSupport::Concern

    module ClassMethods
      def manager?
        true
      end
    end
  end

  include Managers
end

我希望这两个工作:

User.manager?
User.programmer?

但第二次提出

NoMethodError: undefined method `programmer?' for #<Class:0x007f9641beafd0>

如何使用Module#关于?定义类方法?

解决方法

https://github.com/basecamp/concerning/pull/2修正了这个:
class User < ActiveRecord::Base
  concerning :Programmers do
    class_methods do
      def im_a_class_method
        puts "Yes!"
      end
    end
  end
end

安慰:

> User.im_a_class_method
Yes!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读