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.
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?
The method definitions look similar, too: Module methods are defined just like class methods. As with class methods, you call a module method by preceding its name with the module's name and a period, and you reference a constant using the module name and two colons.
"method" is a function that is a attached to an object or class. A module is a group of defined functions, classes, consrants, etc.
A Module is a collection of methods and constants. The methods in a module may be instance methods or module methods. Instance methods appear as methods in a class when the module is included, module methods do not.
Discussion. You can define and access instance variables within a module's instance methods, but you can't actually instantiate a module. A module's instance variables exist only within objects of a class that includes the module.
https://github.com/basecamp/concerning/pull/2 fixed this:
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!
Try this instead:
concerning :Programmers do
included do
def self.programmer?
true
end
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With