Tuesday, 11 January 2022

Ruby on Rails Interview Questions

 Ruby On Rails Questions and Answers

1. What is ORM in Rails?

Object Relational Mapping (ORM) is the technique of accessing a relational database using an object-oriented programming language. Object Relational Mapping is a way to manage database data by "mapping" database tables to classes and instances of classes to rows in those tables.

Active Record is just one of such ORMs

2. What is the difference between a plugin and a gem?

 A gem is just ruby code. It is installed on a machine and it’s available for all ruby applications running on that machine. Rails, rake, json, rspec — are all examples of gems.

Plugin is also ruby code but it is installed in the application folder and only available for that specific application.

Sitemap-generator, etc.

In general, since Rails works well with gems you will find that you would be mostly integrating with gem files and not plugins in general. Most developers release their libraries as gems.

3.What is Active record

Active Record provides a rich API for accessing data within a database

Represent models and their data.

Represent associations between these models.

Represent inheritance hierarchies through related models.

Validate models before they get persisted to the database.

Perform database operations in an object-oriented fashion.

4.What is asset pipeline in Ruby on Rails

The asset pipeline in Ruby on Rails organizes CSS and JavaScript assets in development and compresses and minifies these assets in production.

5. What is a migration in Ruby on rails? Example snippet.

A migration is basically a script that tells Rails how you want to set up or change a database. It's the other part of Active Record magic that allows you to avoid manually going in and writing SQL code to create your database table.

class CreatePublications < ActiveRecord::Migration[5.0]

  def change

    create_table :publications do |t|

      t.string :title

      t.text :description

      t.references :publication_type

      t.integer :publisher_id

      t.string :publisher_type

      t.boolean :single_issue

 

      t.timestamps

    end

    add_index :publications, :publication_type_id

  end

end


6. Give an example to return a collection with all users using Active record

users = User.all

7. Give an example of Active Record API to find all users named David who are Code Artists and sort by created_at in reverse chronological order

users = User.where(name: 'David', occupation: 'Code Artist').order(created_at: :desc)

8. What are validations in Rails. Provide an Example.

Active Record allows you to validate the state of a model before it gets written into the database.

Validation is a very important issue to consider when persisting to the database, so the methods save and update take it into account when running: they return false when validation fails and they didn't actually perform any operation on the database.

class User < ApplicationRecord

  validates :name, presence: true

end


9. Explain concept of Callbacks in rails 

Callbacks are methods that get called at certain moments of an object's life cycle. With callbacks it is possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.

class User < ApplicationRecord

  validates :login, :email, presence: true

 

  before_validation :ensure_login_has_a_value

 

  protected

    def ensure_login_has_a_value

      if login.nil?

        self.login = email unless email.blank?

      end

    end

end

10. What is Single sign on.

Single sign-on (SSO) is a property of access control of multiple related, but independent software systems. With this property a user logs in once and gains access to all systems without being prompted to log in again at each of them. Such as we once log in to google, we are permitted to access the Youtube, Docs, Google Drive etc.

11. What is bundler

Which helps to you manage your gems for the application. After specifying gems in your Gemfile, you need to do a bundle install. If the gem is available in the system, bundle will use that else it will pick up from the rubygems.org.

12. Ruby variables with illustration.

Local variables

Global Variables

Instance variables

Class variables




Local

Global

Instance

Class

Scope

Only within the block or a function

Throughout the program

Limited to one particular instance of a class

Limited to the class that they are defined in

Naming

Local variables begin with a lowercase letter or _(underscore)

Global variables begin with $

Instance variables begin with @

Class variables begin with @@

Initialization

Not necessary to initialize. Using uninitialized local variable is interpreted as call to a method that has no arguments.

Not necessary to initialize. Uninitialized global variables have nil value.

Not necessary to initialize. Uninitialized instance variables have nil value.

Must be initialized before they are used. Using uninitialized class variable results in error.





13. What is the use of Destructive Method?


Distructive methods are used to change the object value permanently by itself using bang (!) operator.

‘sort’ returns a new array and leaves the original unchanged.

‘sort!’ returns the same array with the modification.

The ‘!’ indicates it’s a destructive method. It will overwrite the current array with the new result and returns it.


14. Create a new repository using GIT and Clone a repository

git init

git clone username@host:/path/to/repository


15. Add & Commit (Git commands)

git add <filename>

git commit -m "Commit message"

16. What is the Purpose of “!” and “?” at the end of method names?

Methods ending in ! perform some permanent or potentially dangerous change; for example:

Enumerable#sort returns a sorted version of the object while Enumerable#sort! sorts it in place.

In Rails, ActiveRecord::Base#save returns false if saving failed, while ActiveRecord::Base#save! raises an exception.

Kernel::exit causes a script to exit, while Kernel::exit! does so immediately, bypassing any exit handlers.

Methods ending in ? return a boolean, which makes the code flow even more intuitively like a sentence — if number.zero? reads like “if the number is zero”.

17. What are helpers and how to use helpers in ROR?


Helpers (“view helpers”) are modules that provide methods which are automatically usable in your view. They provide shortcuts to commonly used display code and a way for you to keep the programming out of your views. The purpose of a helper is to simplify the view.

18. Action Controller Parameters


Allows you to choose which attributes should be whitelisted for mass updating and thus prevent accidentally exposing that which shouldn't be exposed. Provides two methods for this purpose: require and permit. The former is used to mark parameters as required. The latter is used to set the parameter as permitted and limit which attributes should be allowed for mass updating.

19. What is Routing? Give example of resource routing and named routes.


The routing module provides URL rewriting in native Ruby. It's a way to redirect incoming requests to controllers and actions. This replaces mod_rewrite rules. Best of all, Rails' Routing works with any web server. Routes are defined in config/routes.rb.

Routes can be named by passing an :as option, allowing for easy reference within your source as name_of_route_url for the full URL and name_of_route_path for the URI path.

Example:

# In routes.rb

get '/login' => 'accounts#login', as: 'login'


# With render, redirect_to, tests, etc.

redirect_to login_url


Use root as a shorthand to name a route for the root path “/”.


# In routes.rb

root to: 'blogs#index'


# would recognize http://www.example.com/ as

params = { controller: 'blogs', action: 'index' }


# and provide these named routes

root_url   # => 'http://www.example.com/'

root_path  # => '/'


Resource routing allows you to quickly declare all of the common routes for a given resourceful controller. Instead of declaring separate routes for your index, show, new, edit, create, update and destroy actions, a resourceful route declares them in a single line of code:


resources :photos


20. Example of ruby string as an interned string.


In Ruby, we can convert a string to a symbol using intern:

"foo".intern # returns :foo


21. Ruby array to JSON and Rails JSON rendering


def autocomplete

     @question = Question.all

     respond_to do |format|

       format.json { render :json => @question }

     end

end




No comments:

Post a Comment