5

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"
JP.
  • 5,507
  • 15
  • 59
  • 100
  • 2
    alert the authors of the `google_search` gem that they've got this problem. They should not depend on `cattr_accessor` from Rails IMO. – horseyguy Jun 09 '10 at 00:14

2 Answers2

10

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

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
Mark Rushakoff
  • 249,864
  • 45
  • 407
  • 398
3

You can get this functionality by including the Ruby Facets gem. Reference the source here:

https://github.com/rubyworks/facets/blob/master/lib/core/facets/cattr.rb

You generally don't need to require all code from the gem. You can selectively require what you want. There are quite a few useful extensions in the gem though.

Kulbir Saini
  • 3,926
  • 1
  • 26
  • 34
Kevin Rood
  • 1,279
  • 3
  • 12
  • 22
  • 1
    This lead me to the rubyworks facets project which moved since this post https://github.com/rubyworks/facets +1 though because the end source code is good – earlonrails May 31 '13 at 00:43