Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is ivar in Rails controller?

I can see ivar term mentioned many times here https://github.com/rails/rails/issues/18950#issuecomment-77924771 but can't find straight forward explanation what is the iVar.

What is it and can this term be used outside controller context?

like image 649
Filip Bartuzi Avatar asked Oct 27 '15 14:10

Filip Bartuzi


People also ask

What is an ivar?

An opaque type that represents an instance variable. iOS 4.0+ iPadOS 4.0+ macOS 10.5+ tvOS 9.0+ watchOS 2.0+

What is instance variable in Rails?

A variable set in Rails controller starting with @ sign are called instance variables. The specialty of instance variables is that they're available in our Rails views. We don't need to pass them explicitly to our Rails views. That's why in the index.

What is a controller Ruby on Rails?

The Rails controller is the logical center of your application. It coordinates the interaction between the user, the views, and the model. The controller is also a home to a number of important ancillary services. It is responsible for routing external requests to internal actions.

What is a class variable in Ruby?

Used declare variables within a class. There are two main types: class variables, which have the same value across all class instances (i.e. static variables), and instance variables, which have different values for each object instance.


1 Answers

ivar stands for instance variable. An instance variable is bound to an object of a given class and, in rails, is mainly used in controllers and views.

This is from the github issue you have posted: 'iVars essentially serve as the recommended "API" between controllers and views.'

For example in your controller:

def new
  @post_ivar = Post.new
end

You can now use this 'ivar' in your view for your new action, i.e. new.haml:

= form_for @post_ivar do |f|
  = f.text_field :headline
  -# ...
like image 89
The F Avatar answered Nov 15 '22 11:11

The F