我想使用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#关于?
定义类方法答案 0 :(得分:7)
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!
答案 1 :(得分:5)
请改为尝试:
concerning :Programmers do
included do
def self.programmer?
true
end
end
end
答案 2 :(得分:2)
快速解决方法:
concerning :MeaningOfLife do
included { extend ClassMethods }
module ClassMethods
...
end