I've worked through a few Rails applications which are using # attribute variables (which are already attr_accessible) in the models. I was having a tough time getting information on this but from what I gather name and #name are the same thing in a model but im probably incorrect on this.
How do these # variables work and why would one ever use the # symbol variables?
To add to the current answers, #instance_variables are from object oriented programming...
In object-oriented programming with classes, an instance variable is a variable defined in a class (i.e. a member variable), for which each instantiated object of the class has a separate copy, or instance.
OOP
"Normal" programming has variables as pieces of data -- strings, integers etc. These are independent & can only interact as part of other functions, depending on their scope.
Object Oriented programming (OOP) can treat variables as pieces of editable data (known as classes). These classes can be invoked, edited and most importantly interacted...
#app/models/product.rb
class Product < ActiveRecord::Base
#-> class
end
def new
#product = Product.new #-> creating a new instance of the class
end
Ruby/Rails is object oriented; it works by giving you a series of objects to load & interact with. The most notable example is with game programming:
The way object orienting works is to invoke/initialize an instance of a class (in our case Product), allowing you to manipulate it.
Class instances hold the object in memory, allowing you to perform actions on the class itself. To do this, you'd store the instance of the class in a variable, allowing you to interact with the variable itself:
#product = Product.new
#product.save
--
Instance variables are only valid within the context of the class:
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def show
#product = Product.new #-> #product only available within ProductsController
end
end
The controllers in Rails are classes, invoked through a rack request:
Request > Rack > Routes > ProductsController.new(request).show > Response
If you want your #instance_variable available in all methods of the class, it has to be at instance level...
# app/controllers/products_controller.rb
class ProductsController < ApplicationController
def show
#product = Product.new
product_save
end
private
def product_save
#product.save #-> #product available in instance of ProductsController class
end
end
The most common use for #instance_variables are to store / manipulate instance-centric data. A good example (for our Product example) could be the stock level:
#app/models/product.rb
class Product < ActiveRecord::Base
def stock
#qty / #orders
end
end
Because you can use getter/setter methods within Ruby, you can define the instance values of a class, accessing them through other instance data:
#product = Product.find x
#product.stock #-> outputs stock value for that product
"#" in front of the name signifies that it is an instance variable of the model class, which is different than a simple ruby variable name. Instance (#) variables can be used in the front-end (views).
For example, you can instantiate a variable #book which is a specific instance of the Book class (which is the model). So when you use #book, you are referring to that specific book you created, rather than the overall class.
There is also a difference in the methods you can call on instance versus class variables.
Variables beginning with # are instance variables, in short they allow other methods of the same class to use them. For example,
class Something
def a_method(name)
#i_variable = name
normal_variable = "hey"
end
def another_method
#i_variable.reverse #can be seen here and used
normal_variable #cannot be seen here and cannot be used, throws an error
end
end
In Rails, I believe instance variables are important because they are visible across the Model, View, Controller parts of the application.
Variables that start with # are instance variables. This means that belong to an instance of a class. So if I had the following class:
class Dog
def initialize(name, breed)
#name = name
#breed = breed
end
end
Everytime I create a Dog, I need to give it a name and a breed.
fido = Dog.new("Fido", "Dalmation")
Because I created instance variables from the name and breed I can get this information from fido.
fido.name => "Fido"
fido.breed => "Dalmation"
If you do this:
def foo
thing = "value"
end
foo
puts thing
You will get
NameError: undefined local variable or method `thing' for main:Object
If you do this:
def foo
#thing = "value"
end
foo
puts #thing
You will get "value"
You see, #variables are visible to the whole class you are operating on, in this case the model.
The #variables are also used a lot in controllers, like this:
def hello
#current_user_name = User.find(params[:user_id]).name
end
# and in the view:
Hello, <%= #current_user_name %>
Because if you didn't use #, you would have made a local variable and that is not accessible by the view.
A var with # is an instance private variable. A var without # is a local method variable.
A variable with # can be accessed on an object's level if the object has a method returning a value of or setting a value to it being attr_accessor, attr_reader or def.
Related
If I have a controller
class MyController < ApplicationController
vals = [...]
def new
...
end
def create
if save
...
else
render 'new'
end
end
how can I make the "vals" variable accessible to both methods? In my "new" view I want to use the "vals" variable for a drop-down menu, but rails is giving me errors. Of course, I could just copy the variable twice, but this solution is inelegant.
As Sebastion mentions a before_ hook / callback is one way to go about it, however as you mentioned it is for a dropdown menu, I am guessing it is a non-changing list, if so I would suggest perhaps using a Constant to define the values, perhaps in the model they are specific to, or if it is to be used in many places a PORO would do nicely to keep things DRY. This will then also allow you to easily access it anywhere, for example in models for a validation check, or to set the options of the dropdown menu in the view, or in the controller if you so wish:
class ExampleModel
DROPDOWN_VALUES = [...].freeze
validates :some_attr, inclusion: { in: DROPDOWN_VALUES }
end
class SomeController < ApplicationController
def new
# can call ExampleModel::DROPDOWN_VALUES here
end
def create
# also here, anywhere actually
end
end
You could use a before_* callback, e.g a before_action, this way you sets your vals variable as an instance one and make it to be available for your both new and create methods, something like:
class SomeController < ApplicationController
before_action :set_vals, only: [:new, :create]
def new
...
# #vals is available here
end
def create
if save
...
# and here
else
render 'new'
end
end
private
def set_vals
#vals = [...]
end
end
A different way from the ones before (although probably just having the instance method is preferred as in Sebastian's solution) is, take advantage of the fact that functions and local variables are called in the same way in ruby and just write:
def vals
#vals ||= [...]
end
and you should be able to access it on the controllers (not the views). If you want it on your views as well you can call at the beginning of the controller
helper_method :vals
If you want to be able to modify vals using vals="some value"
def vals= vals_value
#vals = vals_value
end
Take into account that probably using the intance variable as in Sebastian's solution is preferred, but if you, for whatever reason, are settled on being able to call "vals" instead of "#vals" on the view (for example if you are using send or try), then this should be able to do it for you.
Define in corresponding model
Eg :
class User < ActiveRecord::Base
TYPES = %w{ type1 type2 type3 }
end
and use in ur form like
User::TYPES
=> ["type1", "type2", "type3"]
You can reuse this anywhere in the application.
Let's say I have model Foo with bar column.
I'm quite used to define instance methods of model like this:
class Foo < ActiveRecord::Base
def do_smth
self.bar.capitalize!
end
end
But this is calling getter method on self, which should be just longer way of #bar.capitalize!.
As in Rails some things are hidden from eye (such as initializing Base class) I'm not sure. Will it work?
There is quite a bit of confusion going on here so lets start from the top:
Ruby is all about message passing - when you call a method on an object the implicit recipient is the object itself:
def do_smth
self.bar.capitalize!
end
is equivalent to:
def do_smth
bar.capitalize!
en
So lets take the following example:
class Thing
def initialize
#foo = 1
end
def test
foo # NameError: undefined local variable or method `foo'
end
def test2
#bar # nil
end
end
So, why does this fail? Because in Ruby instance variables are scoped to the instance and only accessible by using the sigil #. Ruby does not automatically map #foo to Thing#foo. Instance variables Ruby even lets you access uninitialized ivars (#bar).
That is unless we create an accessor:
class Thing
def foo
#foo
end
def test
foo # nil
end
end
Which can be done with the shorthand macros attr_reader and attr_accessor.
class Thing
attr_reader :foo # read only
attr_accessor :foo # rw
def test
foo # nil
end
end
This can be quite confusing if you start with Rails without learning how Ruby does OOP since Active Record reads your database tables and creates getters and setters "magically" for all your model attributes.
One thing that you need to remember in that case is that using #some_column will not call any getter/setter methods. Which can cause issues with the Rails dirty state tracking and in cases like date columns which typecast in the setter.
I am new to ruby and programming in general and am trying to grasp a few key concepts.
Given I have a class Dog, with the below characteristics.
class Dog
attr_accessor :type, :popularity, :total
def initialize(type = nil)
#type = type
end
def total_dogs
Dog.count
end
def total
Dog.where(:type => self.type).size
end
def popularity
total.to_f/total_dogs
end
end
What I am trying to understand, is how ruby persists attributes to an instance via getter/setter methods. Its clear to me that if I instantiate a new instance and then save attributes to that instance, those attributes are tied to that instance because if I look at the object the attributes appear as such:
#dog = Dog.new
#dog
=> #<Dog:0x007fa8689ea238 #type=nil>
Its easy for me to understand that as I pass the #dog object around its always going to have the #type attribute as nil.
However, the situation I am having trouble understanding is if I pass this #dog object to another class. Like if I did:
Owner.new(#dog)
When I am in the owner class and I call #dog.popularity how does it know the value of popularity for that instance? At runtime are all methods processed and then that instance just always is tied to the value at the time? Apologies if this makes no sense or I am way off.
When you do
#dog = Dog.new
You do two spearate things
1) Create an instance variable #dog for whatever object your code is currently inside
2) Instantiate a new instance of Dog (with all its methods and attributes) and assign a reference to it to #dog
#dog is a variable, that just happens to point at the Dog instance ("instance of class" generally same meaning as "object") you created at that point. You can set other variables to point to the same instance, and in Ruby this is generally how you pass data around. Objects contain instance variables, and those instance variables point to yet more objects.
Using the assignment operator (i.e "=") you can point a variable at any other object.
To answer your questions in turn:
When I am in the owner class and I call #dog.popularity how does it
know the value of popularity for that instance?
You have to be careful in Ruby (and OO languages in general) to differentiate between class and object in your descriptions and questions. Ruby I'm assuming you are referring to a line of code in the Owner class, and that you intend it to work with an owner object. I'd also assume that #dog is an attribute you have added to Owner.
In which case, Ruby knows because #dog points to the Dog object that you added to owner. Each Dog object has its own copy of all of Dog's instance variables. You do need to take care in Ruby though, because variables point to objects, that you aren't simply passing in the same Dog object to all the owners (i.e. they all effectively share a single dog). So you need to understand when you are creating new instances (via new) and when you are simply handling existing references.
At runtime are all methods processed and then that instance just
always is tied to the value at the time?
No. At runtime, basic Ruby will only perform the assignments that you have coded. Instance variables may not even exist until the code that assigns them has been run. If you use attr_reader etc methods, then the variables will at least exist (but will be nil unless you assign something during initialize)
Niel has a great answer for this, I just want to add something to it.
Counting Dogs :)
You need a class variable to do this..
class Dog
##count = 0 # this is a class variable; all objects created by this class share it
def initialize
##count += 1 # when we create a new Dog, we increment the count
end
def total
##count
end
end
There is another way to do this with "instance variables of the Class object" but that's a bit of an advanced topic.
Accessing Instance Variables
In Ruby, variables are really just references to objects / instances.
> x = 1
=> 1
> x.class
=> Fixnum
> 1.instance_variables
=> []
x is a reference to the object '1', which is an instance of class Fixnum.
The '1' object is an instance of Fixnum which does not contain any instance variables.
It is not different in any way from a reference to a new "Dog" instance.
Similarly, you can say x = Dog.new , then x is a reference to an instance of class Dog.
class Dog
attr_accessor :legs # this defines the 'legs' and 'legs=' methods!
end
x = Dog.new
x.instance_variables
=> [] # if you would assign legs=4 during "initialize", then it would show up here
x.legs = 4 # this is really a method call(!) to the 'legs' method
x.instance_variables # get created when they are first assigned a value
=> [:legs]
It does not matter if you pass such a reference to a method call, or to another class or just evaluate it by itself - Ruby knows it's an object reference, and looks inside the object and it's inheritance chain on how to resolve things.
Resolving Method Names
That was only the partial truth :) When interpreting x.legs , Ruby checks if there is a method in the class-inheritance chain of the object, which responds to that name 'legs'.
It is not magically accessing the instance variable with the same name!
We can define a method 'legs' by doing "attr_reader :legs" or "attr_accessor :legs", or by defining the method ourselves.
class Dog
def legs
4 # most dogs have 4 legs, we don't need a variable for that
end
end
x.legs # this is a method call! it is not directly accessing a :legs instance variable!
=> 4
x.instance_variables
=> [] # there is no instance variable with name ":legs"
and if we try to implement it as a method and an instance variable, this happens: :)
class Dog
attr_accessor :legs # this creates "def legs" and "def legs=" methods behind the scenes
def legs # here we explicitly override the "def legs" method from the line above.
4
end
end
x = Dog.new
x.legs # that's the method call we implemented explicitly
=> 4
x.legs = 3 # we can still assign something to the instance_variable via legs=
=> 3
x.legs # the last definition of a method overrides previous definitions
# e.g. it overrides the automatically generated "legs" method
=> 4
attr_accessor :legs is just a short hand notation for doing this:
class Dog
def legs
#legs
end
def legs=(value)
#legs = value
end
end
there is no magic way instance variable get automatically accessed. They are always accessed through a method, which can be overridden later.
I hope that makes sense to you
When you create an object, you don't need to use the # symbol. The variable is the object. So if you have multiple dogs, you'd do:
myDog = Dog.new(brown)
yourDog = Dog.new(white)
From there, you can say:
yourDog.type #white
myDog.type #brown
What you would NOT do is:
#dog = Dog.new #myDog
#dog = Dog.new #yourDog
If you need multiple versions of an object, you just give them different names. So if you create multiple dogs and pass them to other objects, they will work. For example:
Say your owner class is:
Class Owner
def initialize(pet)
puts "my pet is #{pet.type}"
end
Then using the instance variable would be:
me = Owner.new(myDog) #my pet is brown
you = Owner.new(yourDog) #my pet is white
Both "type" and "popularity" are methods on "dog" instances. Their definition is as follows:
class Dog
# getter
def type
#type
end
def popularity
total.to_f/total_dogs
end
end
This is roughly equivalent to:
class Dog
attr_accessor :type
def popularity
total.to_f/total_dogs
end
end
Note that attr_accessor is just a shortcut for defining a getter method. If you define a method yourself it is pointless to use attr_accessor:
class Dog
attr_accessor :popularity
# this will override getter defined by attr_accessor
def popularity
total.to_f/total_dogs
end
end
Back to your question: #dog.type invokes type method on #dog which returns its instance variable; #dog.popularity invokes popularity method on #dog which does calculations (as defined by you) on the fly and returns the result. No magic here!
I'm reading the Rails AntiPatterns book, which I'm enjoying a lot. At one point, the author talks about the goodness of composition and it gives an example where an Order class gives the responsibility of conversion (to other formats) to another class, called OrderConverter. The classes are defined as:
class Order < ActiveRecord::Base
def converter
OrderConverter.new(self)
end
end
class OrderConverter
attr_reader :order
def initialize(order)
#order = order
end
def to_xml
# ...
end
def to_json
# ...
end
...
end
And then the author says: "In this way, you give the conversion methods their own home, inside a separate and easily testable class. Exporting the PDF version of an order is now just a matter of call-ing the following:"
#order.converter.to_pdf
Regarding to this, my questions are:
Why do you think that order object is preceded by an #? Shouldn't it be created as:
order = Order.new
And then convert by doing:
order.converter.to_pdf
Why is the attr_reader :order line needed in the OrderConverter? It's so we can access the order from an OrderConverter object? Is it needed to be able to do
order.converter.to_pdf ? We could do that without that attr_reader right?
An instance of Order is passed to the initialize method and stored as an instance variable (using the # syntax : #order). This way, this variable can be accessed from other methods in the converter (the variable has the instance scope) :
class OrderConverter
def to_pdf
#order.items.each do |item|
# Write the order items to the PDF
end
end
end
The attr_reader is not strictly required, but is a convenient way to access the Order object from other methods :
class OrderConverter
def to_pdf
order.items.each do |item|
# Write the order items to the PDF
end
end
end
It will also allow you to get the reference to the order out of any converter instance :
converter.order
The # on the front of the variable makes it an instance variable. If it wasn't there the variable would just be a local variable. I'm guessing that since this is a book about Rails, it's assuming that this code would be in a controller. Variables that controllers want to share across methods or expose in their views need to be instance variables. If this is the case #order was probably created either via parameters from a request or with values pulled from the database.
This probably isn't that significant though, both his example and your example work - I think the author was just showing how a call to the OrderConverter would look, and ignored how the Order object got created.
attr_reader :order creates a "getter" method for the #order instance variable in OrderConverter - it's not needed for to_pdf - it would be used to get the Order back out of the OrderConverter via converter.order. I don't see any need to have this in the code you've given so far, but maybe there's some need for it later.
I have a rails model class
class Model < ActiveRecord::Base
has_many :object_collection
def add_object(object)
object_collection.push object // works
#object_collection.push object // does not work
self.object_collection.push object // works
end
end
I was wondering if someone can please explain to me why the # does not work yet self does i thought these two meant the same
cheers
They are not the same. Consider the following Ruby code:
class Person
attr_accessor :employer
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
The method attr_accessor conveniently generates an attribute reader and writer for you (employer= and employer). You can use these methods to read and write an attribute, which is stored in the instance variable #employer.
Now, we can rewrite the above to the following, which is functionally identical to the code above:
class Person
def employer=(new_employer)
#works_for = new_employer
end
def employer
#works_for
end
end
john = Person.new
john.employer = "ACME"
john.employer # equals "ACME"
Now, the instance variable #employer is no longer used. We chose to write the accessors manually, and have the freedom to pick a different name for the instance variable. In this particular example, the name of the instance variable is different than the name of the attribute accessors. There is nothing that prevents you from doing that.
This is similar to how ActiveRecord stores its attributes internally. They are not stored in instance variables of the same name, that is why your push call to #object_collection does not work.
As you may understand, attribute readers and writers offer a certain abstraction that can hide the implementation details from you. Reading and writing instance variables directly in subclasses is therefore generally considered bad practice.
#foo identifies an instance variable called #foo. foo identified a method called foo.
By default, instance variables in Ruby are private. It means you cannot access the value of an instance variable unless you have some public method that exposes the value.
Those methods are called setters and getters. By convenction, setter and getter have the same name of the instance variable, but this is not a requirement.
class MyClass
def initialize
#foo
end
def foo=(value)
#foo = foo
end
def foo
#foo
end
def an_other_foo=(value)
#foo = foo
end
def an_other_foo
#foo
end
end
Though methods and instance variables can have similar names, thery are different elements.
If this topic is not clear to you, you probably need to stop playing with Rails and go back studying how Ruby works.
In your specific case, object_collection doesn't exist as an instance variable because it's an association method.
They do not mean the same thing. One is an instance variable, the other is a method.
The #foo means "the value of the instance variable foo", where as self.foo means "the value of a call to the method foo on myself".
It is typical for a method foo= to set the #foo instance variable, so I can see how someone new to the language might be confused. I'd encourage you to pick up a book on the ruby language. There's one specifically for people who have done some rails but never learned ruby proper. You often can hack rails without understanding the language or what these statements mean, but you'll be far less productive than someone who spends the small amount of time it takes to learn the ruby language itself.
As a general rule, use the self.foo form whenever you can, as this is less sensitive to changes in the classes definition.