在Ruby中定义类方法
通常,在Rails中编写模型时,使用DSL设置派生对象的各个方面,例如:在Ruby中定义类方法,ruby,ruby-on-rails-3,Ruby,Ruby On Rails 3,通常,在Rails中编写模型时,使用DSL设置派生对象的各个方面,例如: class Question < ActiveRecord::Base has_one :category validates_presence_of :category end 所以,当从类实例化对象时,应该定义方法“parent” 我该怎么做?我的第一个想法是使用模块,但这不是实例方法或类方法。我相信这就是您要寻找的: module QuestionParent module ClassMethod
class Question < ActiveRecord::Base
has_one :category
validates_presence_of :category
end
所以,当从类实例化对象时,应该定义方法“parent”
我该怎么做?我的第一个想法是使用模块,但这不是实例方法或类方法。我相信这就是您要寻找的:
module QuestionParent
module ClassMethods
def inherited(descendant)
descendant.instance_variable_set(:@parent, parent.dup)
super
end
def parent(args=nil)
@parent ||= args
end
end
module InstanceMethods
def parent
self.send self.class.parent.to_sym
end
end
def self.included(receiver)
receiver.extend ClassMethods
receiver.send :include, InstanceMethods
end
end
class Question
include QuestionParent
attr_accessor :category
parent :category
end
产生:
q = Question.new
q.category = 'a category'
puts q.parent
a category
这样做的目的是添加一个类方法
parent
,当一个实例在InstanceMethod
中调用parent
时,它将定义类变量@parent
,调用@parent
符号(这里是category
)。正如您所描述的,有一个类方法(称为parent:category
和一个实例方法(q.parent
)。您是否只需要将q.parent
添加到别名q.category
?在本例中,是的,请定义parent;category;end;+1。这是一种常见的ruby习惯用法,允许include
同时添加类和实例方法。谢谢@heelhook,我得到了NameError:uninitialized class variable@@parent In question parent::InstanceMethods执行您的充足的代码…想知道应该在哪里定义吗?@juwiley我刚刚意识到我是用q.category
而不是q.parent
进行测试的。很抱歉,我在答案中重述了代码。我还遇到了对类似技术有更深入解释的代码
q = Question.new
q.category = 'a category'
puts q.parent
a category