我正在尝试使用google_search ruby库(代码如下),但它抱怨“cattr_accessor是一个未定义的方法”--你知道为什么会这样吗?或者我该如何修复它?
require 'rubygems'
require 'google_search'
GoogleSearch.web :q => "pink floyd"发布于 2010-06-09 08:06:47
cattr_accessor似乎是一个Rails扩展that acts like attr_accessor, but is accessible on both the class and its instances。
如果您想复制cattr_accessor方法的源代码,请查看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发布于 2011-08-26 22:42:33
您可以通过包含Ruby Facets gem来获得此功能。请在此处引用源代码:
https://github.com/rubyworks/facets/blob/master/lib/core/facets/cattr.rb
您通常不需要来自gem的所有代码。您可以有选择地请求您想要的内容。不过,gem中有相当多有用的扩展。
https://stackoverflow.com/questions/3002247
复制相似问题