Forum: Ruby on Rails @ vs self in models?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2007-04-06 04:30
(Received via mailing list)
i've seen both of these syntaxes before and have also used both in my
own models:

class Foo
  def get_bar
    @bar
  end
end

and

class Foo
  def get_bar
    self.bar
  end
end

seemingly with no difference... i'm a nuby though so could anyone
enlighten me to the differences if there are any?

thanks,
jeff
8310c5a7c769345114597bcdef111488?d=identicon&s=25 Ben Munat (Guest)
on 2007-04-06 05:05
(Received via mailing list)
@bar is an instance variable... self.bar would be a method. Try doing
this code in irb and you'll see that calling get_bar in the first
version returns nil, while calling it on the second version throws a
NoMethodError.

b
D69d23d8e811e8ab2a8593380d6ede63?d=identicon&s=25 Jeff Emminger (jemminger)
on 2007-04-06 17:58
(Received via mailing list)
aha!  i guess then the reason it has worked in RoR models is due to AR
creating attr_accessors for the table columns, so calling
model.some_col was returning @some_col... thanks for clearing that up
E811b5337bcad19d52c8fed3a0ea0075?d=identicon&s=25 John Miller (jfmiller28)
on 2007-04-06 20:00
Jeff Emminger wrote:
> i've seen both of these syntaxes before and have also used both in my
> own models:
>
> class Foo
>   def get_bar
>     @bar
>   end
> end
>
> and
>
> class Foo
>   def get_bar
>     self.bar
>   end
> end
>
> seemingly with no difference... i'm a nuby though so could anyone
> enlighten me to the differences if there are any?
>
> thanks,
> jeff

This can be a real Gotcha in ActiveRecord.  AR uses the *_missing
methods to give the illusion that it knows what columns you have in your
table.  I believe that using the instance variable (@bar) now spews lots
of depreciation noeses onto stdout.  Good programming practice it to
used the method call because you can then override that method call in
your class and massage the data before it goes out (or comes in).  This
can eliminate the need for the get_* functions.

def bar
  retval = self[:bar]
  #do interesting thing with retval here
  retval
end

John Miller
This topic is locked and can not be replied to.