Kri*_*ris 5 ruby ruby-on-rails
我在引擎样式插件中有一些代码,其中包含一些模型.在我的应用程序中,我想扩展其中一个模型.我已经设法通过在初始化程序中包含一个模块,将实例和类方法添加到相关模型中.
但是,我似乎无法添加关联,回调等.我得到'找不到方法'错误.
/libs/qwerty/core.rb
module Qwerty
module Core
module Extensions
module User
# Instance Methods Go Here
# Class Methods
module ClassMethods
has_many :hits, :uniq => true # no method found
before_validation_on_create :generate_code # no method found
def something # works!
"something"
end
end
def self.included(base)
base.extend(ClassMethods)
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
/initializers/qwerty.rb
require 'qwerty/core/user'
User.send :include, Qwerty::Core::Extensions::User
Run Code Online (Sandbox Code Playgroud)
Sub*_*age 14
你应该能够做到这一点.更简洁恕我直言.
module Qwerty::Core::Extensions::User
def self.included(base)
base.class_eval do
has_many :hits, :uniq => true
before_validation_on_create :generate_code
end
end
end
Run Code Online (Sandbox Code Playgroud)
我认为这应该有效
module Qwerty
module Core
module Extensions
module User
# Instance Methods Go Here
# Class Methods
module ClassMethods
def relate
has_many :hits, :uniq => true # no method found
before_validation_on_create :generate_code # no method found
end
def something # works!
"something"
end
end
def self.included(base)
base.extend(ClassMethods).relate
end
end
end
end
end
Run Code Online (Sandbox Code Playgroud)
旧代码是错误的,因为验证和关联是在模块加载时调用的,并且此模块对ActiveRecord一无所知.这是Ruby的一般方面,类或模块体内的代码在加载时直接调用.你不希望这样.要解决这个问题,您可以使用上述解决方案.
在Rails 3中,这听起来像ActiveSupport :: Concern的一个很好的用例:
module Qwerty::Core::Extensions::User
extend ActiveSupport::Concern
included do
has_many :hits, :uniq => true
before_validation_on_create :generate_code
end
end
class User
include Querty::Core::Extensions::User
# ...
end
Run Code Online (Sandbox Code Playgroud)
以下是我发现的ActiveSupport :: Concern文档和最有用的博客文章.
| 归档时间: |
|
| 查看次数: |
5167 次 |
| 最近记录: |