Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I define class methods with Module#concerning?

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?

like image 649
John Naegle Avatar asked Dec 23 '13 18:12

John Naegle


People also ask

How do you call a method in a module?

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.

Are modules and methods same?

"method" is a function that is a attached to an object or class. A module is a group of defined functions, classes, consrants, etc.

Is a method a module?

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.

Can we define module inside class Ruby?

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.


2 Answers

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!
like image 121
John Naegle Avatar answered Oct 05 '22 09:10

John Naegle


Try this instead:

concerning :Programmers do
  included do
    def self.programmer?
      true
    end
  end
end
like image 27
Rob Avatar answered Oct 05 '22 09:10

Rob