Ruby on Rails Sunday, July 31, 2011

wow thanx!

> > For example @user
> > -> user_controller =
> > What would the difference be between the instance variable and the
> > self.user inside the controller method.
> Lets see:
> class Dog
>   def bark
>     @color = "black"
>     puts "woof"
>   end
>   def color
>     translate_to_german(@color)
>   end
>   def translate_to_german(word)
>     if word == "black"
>       'schwartz'
>     else
>       'not known'
>     end
>   end
>   def show
>     puts @color
>     puts self.color *
>   end
> end

* so in this context self.color calls the color method of the Dog
class for the d object (d.color) . What if we omitted "self" , would
rails execute the color method with the same result?

> d =
> d.bark
> --output:--
> woof
> black       #@color
> schwartz   #self.color

> > You can just assign to the instance variable and you're done
> > since it will be accessible in the controller and view for as long as
> > the sess_controller lasts.
> Yes, but what if later you decide that you want to alter the value that
> is assigned to the instance variable before doing the assignment?  Then
> you would have to look through your code and find every line where you
> have written @var_name = ...., and change it.  What if your program was
> 10 million lines long?  Would you want to do that?  How long would it
> take you?  Two years?  Twenty years?
> If you always access instance variables using getters and setters, you
> have the flexibility to change the value that is set or the value that
> is retrieved.  For instance suppose you were doing calculations in feet
> and you decided you needed to do the calculations in meters.  Without
> changing the user interface, you could make those changes in the getter
> and setter methods.  The user could still enter the value in feet, and
> then your
> setter could convert to meters and save that value instead.  Your getter
> could then convert the value back to feet and return it.
> If you are interested in more examples, you can search google for
> something like 'why
> getters and setters'

Ok, i think i kind of understand what you mean here, but need some
examples. I will google it.
Getters and setters are the same with the attr_accessor but we can't
use it in a controller because its an ActiveRecord attribute, right?

So inside the getter and setter we can define what is going to be
stored to or retrieved from an instant variable.

def online_user= (user)
@current_user = user
#or any other code we want to write

def online_user
# or any other code we want to write

Must the name of the "methods" (online_user) be the same with the
instant varialbe (@current_user) inside the "method" ?

You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to
To unsubscribe from this group, send email to
For more options, visit this group at

No comments:

Post a Comment