cattr_accessor

7 views
Skip to first unread message

momi

unread,
Sep 5, 2006, 4:36:41 AM9/5/06
to rubyonra...@googlegroups.com
Hi,

i've been playing with ror for a little over two months now, and was
wondering wether someone could explain to me what was
cattr_accessor
and if it is still in use. . . i looked up in api.rubyonrails.com and
coulnd't find any documentation...

is it a useful/worth learning method? what do u use it for?

--
Posted via http://www.ruby-forum.com/.

Greg H

unread,
Sep 5, 2006, 5:27:40 AM9/5/06
to rubyonra...@googlegroups.com
I'd just asked this not long ago  :) - here's a copy/paste of the reponse from David

Hi --

On Mon, 4 Sep 2006, Greg H wrote:

> Had a quick look at this (e.g. cattr_reader - extract below) - still I
> little unclear to me.  Do you think you could run what "cattr_accessor" does
> in layman's terms at all?  e.g. difference between class & instant
> aspects.   (sorry - the penny hasn't dropped yet :)  )

In layman's terms, I'd describe it as, "A computer programming thing"
:-)  But here's a somewhat super-layman explanation.

Ruby has an attr_* family of methods:

  class C
    attr_accessor :x
    attr_reader :y
    attr_writer :z
  end

These attr_* methods are meta-methods; that is, calling them actually
results in the automatic creation of other methods.  In the example
above, instances of C will have the following methods:

  x     # reader
  x=    # writer
  y     # reader
  z=    # writer

The idea is to provide a convenient way to get and/or set state in an
object:

  c = C.new
  c.x = 1    # actually a call to the x= method!
  puts c.x   # a call to the x method

The way this works is that the reader and writer methods (x, x=, etc.)
store/retrieve values in/from instance variables.  If you wrote them
out, the methods that the attr_* methods create for you would look
like this:

  class C
    def x  # read "attribute" (i.e ., value of instance variable)
      @x
    end

    def x=(value)  # set "attribute" (i.e., set instance variable)
      @x = value
    end

    def y
      @y
    end

    def z=(value)
      @z = value
    end
  end

In addition to instance variables, Ruby has class variables.  The
purpose of the cattr_* methods is to provide a mechanism exactly like
the above -- but using class variables instead of instance variables.
Furthermore, the set/get operations are available both to instances of
the class, and to the class itself:

  class D
    cattr_accessor :a
  end

  d = D.new
  d.a = 1     # set via an instance
  puts D.a    # get via the class

So it's just a kind of elaboration of the original Ruby attribute
implementation.  To get both the class and its instances to know about
the get and set methods, there have to be two of each.  So this is
what the expanded version of the last example looks like:

  class D
    def self.a     # class get method
      @@a
    end

    def self.a=(value)  # class set method
      @@a = value
    end

    def a            # instance get method
      @@a
    end

    def a=(value)    # instance set method
      @@a = value
    end
  end

I personally consider "cattr" (class attribute) a misnomer.
"Attribute" suggests a property of an object.  Class variables do not
map onto the state of any particular object; they are visible to a
given class, all of its subclasses, and all of the instances of itself
and those subclasses.  So when you save a value in a class variable,
it's a considerable stretch to refer to it as an "attribute".  But
anyway, the above is how it works and what it does.


David

momi

unread,
Sep 5, 2006, 10:52:10 AM9/5/06
to rubyonra...@googlegroups.com
thank you so much for the elaboration.
seems to sit better in the mind.

thanks!

Jim Mundy

unread,
Sep 16, 2006, 1:07:57 PM9/16/06
to rubyonra...@googlegroups.com
cattr_accessor Error - Help Please

My ruby script is throwing the following error when I try to run it. I
thought it was a path problem and did a completely new install. Does
anyone know why I would be getting this error.

I've also pasted a copy of the script below.

$ruby script.rb

/usr/local/lib/ruby/site_ruby/1.8/active_record/base.rb:246: undefined
method `cattr_accessor' for ActiveRecord::Base:Class (NoMethodError)
from
/usr/local/lib/ruby/site_ruby/1.8/rubygems/custom_require.rb:27:in
`require'
from /usr/local/lib/ruby/site_ruby/1.8/active_record.rb:37
from ./db.rb:1
from script.rb:3


Script:

#! /usr/bin/env ruby
$: << '/usr/local/lib/ruby/gems/1.8/gems/activerecord-1.14.2/lib'
require 'db'
require 'activerecord'
require 'config'
require 'faster_csv'

file_dir = File.dirname(__FILE__) + '/files/'
list_of_files = 'files.txt'


unless (ARGV.empty?)
files = ARGV
else
files = IO.readlines(list_of_files)
files.collect!{|file| file.strip}
end

files.each do |filename|
filename = file_dir + filename.strip
puts "Using filename: #{filename}"

unless ( File.exist?( filename ) )
puts "ERROR: #{filename} not found"
else
FasterCSV.foreach(filename) do |row|

tbl_type = row[0]
print "Inserting into #{tbl_type}... "

tbl_info = $field_map[tbl_type]
unless ( tbl_info.nil? )
field_no = tbl_info[:count]
object = tbl_info[:object]

columns = nil
eval %{columns = #{object}.column_names}

#print row.size, ' - ', columns.size, "\n"
if (row.size == columns.size - 1)
new_record = Hash.new
j=0
row.each do |val|
new_record[columns[j+1]] = val
j = j + 1
end

eval %{#{object}.create(new_record)}

puts "done"
else
puts "FAILED"
end
else
puts 'ERROR: Table not found'
end
end
end
end

> def x # read "attribute" (i.e., value of instance variable)

Jason Lillywhite

unread,
Sep 5, 2008, 2:57:15 PM9/5/08
to rubyonra...@googlegroups.com
It seems odd that cattr_* is not in the native Ruby and that you have to
require active support and rubygems to get this to work. Why is this not
built in the native Ruby source?

David A. Black

unread,
Sep 5, 2008, 5:35:59 PM9/5/08
to rubyonra...@googlegroups.com
Hi --

On Fri, 5 Sep 2008, Jason Lillywhite wrote:

>
> It seems odd that cattr_* is not in the native Ruby and that you have to
> require active support and rubygems to get this to work. Why is this not
> built in the native Ruby source?

See my answer on ruby-talk.


David

--
Rails training from David A. Black and Ruby Power and Light:
Intro to Ruby on Rails January 12-15 Fort Lauderdale, FL
Advancing with Rails January 19-22 Fort Lauderdale, FL *
* Co-taught with Patrick Ewing!
See http://www.rubypal.com for details and updates!

Reply all
Reply to author
Forward
0 new messages