本文介绍了cattr_accessor在导轨外部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 google_search ruby​​库(代码如下),但它抱怨说'cattr_accessor是未定义的方法"-关于为什么会这样或如何解决的任何想法?

I'm trying to use the google_search ruby library (code follows) but it complains that 'cattr_accessor is an undefined method' - any ideas why this might be or how I could fix it?

require 'rubygems'
require 'google_search'

GoogleSearch.web :q => "pink floyd"

推荐答案

cattr_accessor似乎是Rails扩展其作用类似于attr_accessor,但在类及其实例上均可访问.

cattr_accessor seems to be a Rails extension that acts like attr_accessor, but is accessible on both the class and its instances.

如果您要复制cattr_accessor方法的源,请查看此文档:

If you want to copy the source of the cattr_accessor method, check out this documentation:

# File vendor/rails/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 46
def cattr_accessor(*syms)
  cattr_reader(*syms)
  cattr_writer(*syms)
end

# File vendor/rails/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 4
def cattr_reader(*syms)
  syms.flatten.each do |sym|
    next if sym.is_a?(Hash)
    class_eval("unless defined? @@\#{sym}\n@@\#{sym} = nil\nend\n\ndef self.\#{sym}\n@@\#{sym}\nend\n\ndef \#{sym}\n@@\#{sym}\nend\n", __FILE__, __LINE__)
  end
end

# File vendor/rails/activesupport/lib/active_support/core_ext/class/attribute_accessors.rb, line 24
def cattr_writer(*syms)
  options = syms.extract_options!
  syms.flatten.each do |sym|
    class_eval("unless defined? @@\#{sym}\n@@\#{sym} = nil\nend\n\ndef self.\#{sym}=(obj)\n@@\#{sym} = obj\nend\n\n\#{\"\ndef \#{sym}=(obj)\n@@\#{sym} = obj\nend\n\" unless options[:instance_writer] == false }\n", __FILE__, __LINE__)
  end
end

这篇关于cattr_accessor在导轨外部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 14:35
查看更多