我有我已经贴到我的用户模型如下:如何使用模块在Rails中扩展类?
module ClassMethods
Devise::Models.config(self, :email_regexp, :password_length)
end
我想要做这样的事情在我的用户模型self.extend ClassMethods
,但我不能完全似乎得到它的权利。我想从设计中直接在我的用户模型中访问这些方法。
我有我已经贴到我的用户模型如下:如何使用模块在Rails中扩展类?
module ClassMethods
Devise::Models.config(self, :email_regexp, :password_length)
end
我想要做这样的事情在我的用户模型self.extend ClassMethods
,但我不能完全似乎得到它的权利。我想从设计中直接在我的用户模型中访问这些方法。
您需要使用ActiveSupport::Concern
这一点。在模块应该用于扩展您插入一个类:
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
然后EHT只有你需要做的事情是include
它要延长Model
!
class User < ActiveRecord::Base
include ModuleName
end
那就是它。欲了解更多信息,请看apidock => ActiveSupport :: Concern!
你有没有尝试过:
require 'my_module'
include MyModule::ClassMethods
我不知道,如果我得到的一切权利,但如果你想添加功能,当模块包含的类,你可以使用self.included
module ClassMethods
def self.included(base)
Devise::Models.config(base, :email_regexp, :password_length)
end
end
我能想到的最好的办法是:
module Devisable
def included(base)
base.class_eval do
Devise::Models.config(self, :email_regexp, :password_length)
end
end
end
class_eval是插入代码的好方法,可以避免与base
或ClassMethods
混淆。
我不这样说得很对;你是对的,指出这些都是宝石,但我认为这将扩展包含其中的父类,而不是我所在的类。 – cjm2671 2011-12-14 12:22:07