简体   繁体   中英

How do I extend a class in Rails using a module?

I've got the following I've pasted into my user model:

module ClassMethods
  Devise::Models.config(self, :email_regexp, :password_length)
end

I want to do something like self.extend ClassMethods in my User model, but I can't quite seem to get it right. I want to make these methods from devise accessible directly in my User model.

Have you tried just:

require 'my_module'
include MyModule::ClassMethods

You need to use ActiveSupport::Concern for this. In the module that should be used to extend a class you insert:

module ModuleName
     extend ActiveSupport::Concern
     ....
     ....
     ....
     module ClassMethods
           # the Class Methos you want to add to other Classes here
     end

     module InstanceMethods
           # the instance Methods you want to add to other classes here
     end
end

And then eht only thing you need to do is include it in the Model you want to extend!

class User < ActiveRecord::Base
     include ModuleName
end

Thats it. For more info have a look at apidock => ActiveSupport::Concern!

I'm not sure if I got everything right but if you want add functionality to the class when the module is included you can use self.included

module ClassMethods

  def self.included( base )
    Devise::Models.config( base, :email_regexp, :password_length )
  end

end

Best way I can think is:

module Devisable
  def included(base)
    base.class_eval do
      Devise::Models.config(self, :email_regexp, :password_length)
    end
  end
end

class_eval is a good way of inserting code and keeping you from messing around with base or ClassMethods .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM