Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Ruby中定义类方法_Ruby_Ruby On Rails 3 - Fatal编程技术网

在Ruby中定义类方法

在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

通常,在Rails中编写模型时,使用DSL设置派生对象的各个方面,例如:

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