I'd like to define class method using Module#concerning (https://github.com/37signals/concerning - part of Rails 4.1). This would let me move modules that are used by a single class back into the class.
我想使用Module#related(https://github.com/37signals/concerning - Rails 4.1的一部分)来定义类方法。这样我就可以将单个类使用的模块移回到类中。
However, it seems that I can't define class methods. Given this:
但是,似乎我无法定义类方法。鉴于这种:
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
I would expect both these to work:
我希望这两个工作:
User.manager?
User.programmer?
But the second raises
但第二次提出
NoMethodError: undefined method `programmer?' for #<Class:0x007f9641beafd0>
How can I define class methods using Module#concerning?
如何使用Module#关于?定义类方法?
3 个解决方案
#1
7
https://github.com/basecamp/concerning/pull/2 fixed this:
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
Console:
> User.im_a_class_method
Yes!
#2
5
Try this instead:
试试这个:
concerning :Programmers do
included do
def self.programmer?
true
end
end
end
#3
2
Quick workaround:
concerning :MeaningOfLife do
included { extend ClassMethods }
module ClassMethods
...
end
#1
7
https://github.com/basecamp/concerning/pull/2 fixed this:
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
Console:
> User.im_a_class_method
Yes!
#2
5
Try this instead:
试试这个:
concerning :Programmers do
included do
def self.programmer?
true
end
end
end
#3
2
Quick workaround:
concerning :MeaningOfLife do
included { extend ClassMethods }
module ClassMethods
...
end