Skip to main content

Interview question for ruby on rails

1. Why Ruby on Rails?
Ans: There are lot of advantages of using ruby on rails
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept
6. Rest Support
7. Rack support
8. Action Mailer
9. Rpc support
10. Rexml Support
2. Explain about the programming language ruby?
Ruby is the brain child of a Japanese programmer Matz. He created Ruby. It is a cross platform object oriented language. It helps you in knowing what your code does in your application. With legacy code it gives you the power of administration and organization tasks. Being open source, it did go into great lengths of development.
3. Explain about ruby names?
Classes, variables, methods, constants and modules can be referred by ruby names. When you want to distinguish between various names you can specify that by the first character of the name. Some of the names are used as reserve words which should not be used for any other purpose. A name can be lowercase letter, upper case letter, number, or an underscore, make sure that you follow the name by name characters.
4. What is the Difference between Symbol and String?
Ans: Symbol are same like string but both behaviors is different based on object_id, memory and process time (cpu time) Strings are mutable , Symbols are immutable.
Mutable objects can be changed after assignment while immutable objects can only be overwritten. For example
p "string object jak".object_id #=> 22956070
p "string object jak".object_id #=> 22956030
p "string object jak".object_id #=> 22956090
p :symbol_object_jak.object_id #=> 247378
p :symbol_object_jak.object_id #=> 247378
p :symbol_object_jak.object_id #=> 247378
p " string object jak ".to_sym.object_id #=> 247518
p " string object jak ".to_sym.object_id #=> 247518
p " string object jak ".to_sym.object_id #=> 247518
p :symbol_object_jak.to_s.object_id #=> 22704460
p :symbol_object_jak.to_s.object_id #=> 22687010
p :symbol_object_jak.to_s.object_id #=> 21141310
And also it will differ by process time
For example:
Testing two symbol values for equality (or non-equality) is faster than testing two string values for equality,
Note : Each unique string value has an associated symbol
5. What is Session and Cookies?
Ans: Session: are used to store user information on the server side.
cookies: are used to store information on the browser side or we can say client side
Session : say session[:user] = “arunkumar” it remains when the browser is not closed
6. What is request.xhr?
Ans: A request.xhr tells the controller that the new Ajax request has come, It always return Boolean values (TRUE or FALSE)
7. What is MVC? and how it Works?
Ans: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like this: Request first comes to the controller, controller finds and appropriate view and interacts with model, model interacts with your database and send the response to controller then controller based on the response give the output parameter to view, for Example your url is something like this:
http://localhost:3000/users/new
here users is your controller and new is your method, there must be a file in your views/users folder named new.html.erb, so once the submit button is pressed, User model or whatever defined in the rhtml form_for syntax, will be called and values will be stored into the database.
8. What things we can define in the model?
Ans: There are lot of things you can define in models few are:
1. Validations (like validates_presence_of, numeracility_of, format_of etc.)
2. Relationships(like has_one, has_many, HABTM etc.)
3. Callbacks(like before_save, after_save, before_create etc.)
4. Suppose you installed a plugin say validation_group, So you can also define validation_group settings in your model
5. ROR Queries in Sql
6. Active record Associations Relationship
9. What is ORM in Rails?
Ans: ORM tends for Object-Relationship-Model, it means that your Classes are mapped to table in the database, and Objects are directly mapped to the rows in the table.
10. How many Types of Associations Relationships does a Model has?
Ans: When you have more than one model in your rails application, you would need to create connection between those models. You can do this via associations. Active Record supports three types of associations:
  • one-to-one : A one-to-one relationship exists when one item has exactly one of another item. For example, a person has exactly one birthday or a dog has exactly one owner.
  • one-to-many : A one-to-many relationship exists when a single object can be a member of many other objects. For instance, one subject can have many books.
  • many-to-many : A many-to-many relationship exists when the first object is related to one or more of a second object, and the second object is related to one or many of the first object.
You indicate these associations by adding declarations to your models: has_one, has_many, belongs_to, and has_and_belongs_to_many.
11. Difference between render and redirect?
Ans:
render example:
 render :partial 
 render :new
  It will render the template new.rhtml without
  calling or redirecting to the new action.

redirect example: 
 redirect_to :controller => ‘users’, :action => ‘new’
  It forces the clients browser to request the
  new action. 
 12. What is the Difference between Static and Dynamic Scaffolding?
Ans: The Syntax of Static Scaffold is like this:
ruby script/generate scaffold User Comment
Where Comment is the model and User is your controller, So all n all static scaffold takes 2 parameter i.e your controller name and model name, whereas in dynamic scaffolding you have to define controller and model one by one.
13. How you run your Rails Application without creating database ?
Ans: You can run application by uncomment the line in environment.rb
Path => rootpath conf/ environment.rb
# Skip frameworks you're not going to use (only works if using vendor/rails)
    config.frameworks -= [ :action_web_service, :action_mailer,:active_record ]
14. How to use sql db or mysql db. without defining it in the database.yml
Ans: You can use ActiveRecord anywhere!
require 'rubygems'

require 'active_record'

ActiveRecord::Base.establish_connection({

:adapter => 'postgresql',

:user => 'foo',

:password => 'bar',

:database => 'whatever'

})

class Task <>

set_table_tame "a_legacy_thingie"

def utility_methods

update_attribute(:title, "yep")

end

end

Task.find(:first)

Etcetera. It’s ActiveRecord, you know what to do. Going wild:

ActiveRecord::Base.establish_connection(:adapter => "sqlite3", 
:dbfile => ":memory:")

ActiveRecord::Schema.define(:version => 1) do

create_table :posts do |t|

t.string :title

t.text :excerpt, :body

end

end

class Post <>

validates_presence_of :title

end

Post.create(:title => "A new post!")

Post.create(:title => "Another post", 
:excerpt => "The excerpt is an excerpt.")

puts Post.count
15. What are helpers and how to use helpers in ROR?
Ans: 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. It’s best if the view file (RHTML/RXML) is short and sweet, so you can see the structure of the output.
16. What is Active Record?
Ans: Active Record are like Object Relational Mapping(ORM), where classes are mapped to table , objects are mapped to columns and object attributes are mapped to data in the table
17. Ruby Support Single Inheritance/Multiple Inheritance or Both?
Ans: Ruby Supports only Single Inheritance.
You can achieve Multiple Inheritance through MIXIN concept means you achieve using module by including it with classes.
18. How many types of callbacks available in ROR?
Ans:
  • (-) save
  • (-) valid
  • (1) before_validation
  • (2) before_validation_on_create
  • (-) validate
  • (-) validate_on_create
  • (3) after_validation
  • (4) after_validation_on_create
  • (5) before_save
  • (6) before_create
  • (-) create
  • (7) after_create
  • (8) after_save

19. WHAT CAN RAILS MIGRATION DO?

ANS:

  • create_table(name, options)
  • drop_table(name)
  • rename_table(old_name, new_name)
  • add_column(table_name, column_name, type, options)
  • rename_column(table_name, column_name, new_column_name)
  • change_column(table_name, column_name, type, options)
  • remove_column(table_name, column_name)
  • add_index(table_name, column_name, index_type)
  • remove_index(table_name, column_name)
Migrations support all the basic data types: string, text, integer, float, datetime, timestamp, time, date, binary and boolean:
  • string - is for small data types such as a title.
  • text - is for longer pieces of textual data, such as the description.
  • integer - is for whole numbers.
  • float - is for decimals.
  • datetime and timestamp - store the date and time into a column.
  • date and time - store either the date only or time only.
  • binary - is for storing data such as images, audio, or movies.
  • boolean - is for storing true or false values.
Valid column options are:
  • limit ( :limit => “50” )
  • default (:default => “blah” )
  • null (:null => false implies NOT NULL)
20. What is the naming conventions for methods that return a boolean result?
Ans: Methods that return a boolean result are typically named with a ending question mark. For example: def active? return true #just always returning true end
21. How do the following methods differ: @my_string.strip and @my_string.strip! ?
Ans: The strip! method modifies the variable directly. Calling strip (without the !) returns a copy of the variable with the modifications, the original variable is not altered.
22. What’s the difference in scope for these two variables: @name and @@name?
Ans: @name is an instance variable and @@name is a class variable
23. What is the log that has to seen to check for an error in ruby rails?
Ans: Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you’re having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application’s execution.
24. What is the use of global variable $ in Ruby?
Ans: A class variable starts with an @@ sign which is immediately followed by upper or lower case letter. You can also put some name characters after the letters which stand to be a pure optional. A class variable can be shared among all the objects of a class. A single copy of a class variable exists for each and every given class.
To write a global variable you start the variable with a $ sign which should be followed by a name character. Ruby defines a number of global variables which also include other punctuation characters such as $_ and $-k.
For example: If you declare one variable as global we can access any where, where as class variable visibility only in the class Example
class Test
def h
 $a = 5
 @b = 4
Â
while $a > 0
puts $a
$a= $a – 1
end
end
end
test = Test.new
test.h
puts $a                    # 5
puts @b                   #nil
25. Where does the start_tabnav gets informations for tabs rendering in ruby rail?
Ans: The main Symbol let the start_tabnav method know to look for a special MainTabnav class where all the magic happens
26. What is the Install rail package?
Ans: There are several packages that you can download and install. The prebuilt Rails installer called Install rail which currently is only for Windows
27. What is the log that has to seen to check for an error in ruby rails?
Ans: Rails will report errors from Apache in log/apache.log and errors from the Ruby code in log/development.log. If you’re having a problem, do have a look at what these logs are saying. On Unix and Mac OS X you may run tail -f log/development.log in a separate terminal to monitor your application’s execution.
28. What is the use of super in ruby rails?
Ans: Ruby uses the super keyword to call the superclass (Parent class) implementation of the current method
29. What is the difference between nil and false in ruby?
Ans: False is a boolean datatype, Nil is not a data type it have object_id 4
30. How is class methods defined in Ruby?
Ans: A:def self.methodname
——–
——–
end
or
def classname.methodname
——–
——–
end
31. How is object methods defined in Ruby?
Ans:
class jak
def method1
——–
——–
end
end
obj=jak.new
It is single object
def obj.object_method_one
——–
——–
end
obj.Send(object_method_every)
It will be created every for every object creation
32. What are the priority of operators available in Ruby ?
Ans: Something that used in an expression to manipulate objects such as + (plus), – (minus), * (multiply), and / (divide). You can also use operators to do comparisons,such as with <, >, and &&. The priority is based on “BODMAS”
33. What are the looping structures available in Ruby?
Ans: for..in
untill..end
while..end
do..end
Note: You can also use each to iterate a array as loop not exactly like loop
34. What are the object-oriented programming features supported by Ruby and how multiple inheritance supported in ?
Ans: Classes,Objects,Inheritance,Singleton methods,polymorphism(accomplished by over riding and overloading) are some oo concepts supported by ruby. Multiple inheritance supported using Mixin concept.
35. What is the scope of a local variable in Ruby and define it scope ?
Ans: A new scope for a local variable is introduced in the toplevel, a class (module) definition, a method defintion. In a procedure block a new scope is introduced but you can access to a local variable outside the block.
The scope in a block is special because a local variable should be localized in Thread and Proc objects.
36. How is an enumerator iterator handled in Ruby?
Ans: Iterator is handled using keyword ‘each’ in ruby.
For example
number=[1,2,3]
then we can use iterator as
number.each do |i|
puts i
end
Above prints the values of an array $no which is accomplished using iterator.
37. How is visibility of methods changed in Ruby (Encapsulation)?
Ans: By applying the access modifier : Public , Private and Protected access Modifier
38. What is the use of load,require, auto_load,require_relative in Ruby?
Ans: A method that loads and processes the Ruby code from a separate file, including whatever classes, modules, methods, and constants are in that file into the current scope. load is similar, but rather than performing the inclusion operation once, it reprocesses the code every time load is called.
auto_load – Whenever the interpreter call the method that time only it will initiate the method in hat file.
require_relative – It it to load local folder files
39.What is agile development? What are the strenghts?
Agile software development refers to a group of software development methodologies based on iterative development, where requirements and solutions evolve through collaboration between self-organizing cross-functional teams
Advantages:
  • Customer satisfaction by rapid, continuous delivery of useful software
  • Working software is delivered frequently (weeks rather than months)
  • Projects are built around motivated individuals, who should be trusted
  • Continuous attention to technical excellence and good design
  • Simplicity
  • Self-organizing teams
  • Regular adaptation to changing circumstances
40.ORM
ORM:
Active Record connects business objects and database tables to create a domain model where logic and data are presented in one.
Active Record‘s main contribution to the pattern is to relieve the original of two stunning problems
1. lack of associations and
2. inheritance
By adding a simple domain language-like set of macros to describe the Single Table Inheritance pattern and latter, Active Record narrows the gap of functionality between the data mapper and active record approach.
Here is the lift of Major features of ORM in rails:
1. In rails ,with the help of ORM concept by using Active record as a bridge automated mapping can be done between classes and tables , attributes and columns.
2. By using the ORM the association can be done easily between objects controlled by simple meta-programming macros.
3. By using this the aggregations of value can be controlled easily by simple meta-programming access(i.e) it expresses relationships like “Account [is] composed of Money [among other things]” or “Person [is] composed of [an] address” etc..
4. By using the ORM we can specify the validation rules for both the existing and new objects.So it will be easily identified to get validated.
5. This can be used as the callbacks as methods or queues on the entire software life cycle .
for example: before_save,before_destroy,after_save
so these callbacks can be easily called.
6. The ORM acts as the Observers for the entire life cycle
7. This ORM maintains the inheritance in well structured manner(hierarchy)
8. This maintains the Transactions
we are supposed to use transaction blocks whenever you have a number of statements that must be executed together or not at all.
example:
The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa.
So by using the ORM the transactions can be done easily.
9. Reflections on columns, associations, and aggregations can be easily done with ORM
10. by using the ORM we can use Direct manipulation instead of using service invocation.
41.Difference between Application server and Web Server
apache, nginx, IIS are web servers
mongrel, webrick, phusion passenger are app servers
App server is something which works with particular programming language and parses and executes the code
since mongrel and webrick can only work with rails, so they are app servers
Web servers are servers which can take the request from the browser.
Web servers normally works on port 80 though we can change the port in configuration
since mongrel and webrick can take that request directly, so they can be thought of as web servers but web servers do have a lot of other functionality like request pipeline, load balancing etc.
App servers lack these functionalities.
42.Difference between Validations, Callbacks and Observers
 Validations allow you to ensure that only valid data is stored in your database.
Example: validates_presence_of :user_name, :password
validates_numericality_of :valueWe can write custom validation also as def validate
errors.add(:price, “should be a positive value”) if price.nil?|| price < 0.01
end
Callbacks and observers allow you to trigger logic before or after an alteration of an object’s state.
Callbacks are methods that get called at certain moments of an object’s life cycle. With callbacks it’s possible to write code that will run whenever an Active Record object is created, saved, updated, deleted, validated, or loaded from the database.
Callbacks are hooks into the life cycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they’re validated (by overwriting before_validation)
Observers are similar to callbacks, but with important differences. Whereas callbacks can pollute a model with code that isn’t directly related to its purpose, observers allow you to add the same functionality outside of a model. For example, it could be argued that a User model should not include code to send registration confirmation emails. Whenever you use callbacks with code that isn’t directly related to your model, you may want to consider creating an observer instead.
43.What are filters? and how many types of filters are there in ruby?
Filters are methods that are run before, after or “around” a controller action.
Filters are inherited, so if you set a filter on ApplicationController, it will be run on every controller in your application.
Filter can take one of three forms: method reference (symbol), external class, or inline method (proc).
44.Difference between  Gem and Plugin
GEM
1. Gem is a packaged ruby application using the packaging system defined by RubyGems.
2. Rails itself is a Gem
3. We can install,upgrade and query the gem version.
4. Gem installed for Ruby interpreter can be used system-wide by that interpreter.
Plugin
1. Plugin is an extension of Rails Framework.
2. Can not be upgraded by using a command. To upgrade one have to uninstall and then install upgraded version.
3. Has to be hooked into rails application. (has to have init.rb)
4. Have an install.rb file.
5. Can only be used application wide.
45.Mixins in Ruby

When a class can inherit features from more than one parent class, the class is supposed to show multiple inheritance.

 Ruby does not suppoprt mutiple inheritance directly but Ruby Modules have another, wonderful use. At a stroke, they pretty much eliminate the need for multiple inheritance, providing a facility called a mixin.
Mixins give you a wonderfully controlled way of adding functionality to classes. However, their true power comes out when the code in the mixin starts to interact with code in the class that uses it.
Let us examine the following sample code to gain an understand of mixin:
module A
def a1
end
def a2
end
end
module B
def b1
end
def b2
end
endclass Sample
include A
include B
def s1
end
end samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
Module A consists of the methods a1 and a2. Module B consists of the methods b1 and b2. The class Sample includes both modules A and B. The class Sample can access all four methods, namely, a1, a2, b1, and b2. Therefore, you can see that the class Sample inherits from both the modules. Thus you can say the class Sample shows multiple inheritance or a mixin.

Comments

Popular posts from this blog

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).?

Gem::LoadError (Specified 'mysql2' for database adapter, but the gem is not loaded. Add `gem 'mysql2'` to your Gemfile (and ensure its version is at the minimum required by ActiveRecord).) In rails?


1)change the gemfile in mysql version
 gem 'mysql2'

2)Change to mysql2 version
 gem 'mysql2','0.3.20'

Active Scaffold : Add radio buttons to your form ruby on rails ?

Active Scaffold : Add radio buttons to your form ruby on rails ?

The way to add radio buttons to your active scaffold create/update from is as shown below

#Controller

class UsersController < ApplicationController
active_scaffold :user do |config|
config.label = “Users”
config.columns = [:name, :gender]
config.columns[:gender].form_ui = :radio
config.columns[:gender].options[:options] = [['Male', '1'], ['Female','2']]
end
end

Get the Current url in ruby on rails

request.refererrequest.fullpathrequest.fullpath.split("?")[0]request.referer or request.env['HTTP_REFERER'] your controller to get the referer url. 

--------------------
request.original_url
request.url
request.host_with_port
<link rel="canonical" href="<%= request.url %>" />
<%=request.path%>
How can I get the current absolute URL in my Ruby on Rails view?
The request.request_uri only returns the relative URL.
request.env['REQUEST_URI']

 For Rails 3.2 or Rails 4 you should use request.original_url to get the current URL. More detail.

For Rails 3: You want "#{request.protocol}#{request.host_with_port}#{request.fullpath}", since request.url is now deprecated.

For Rails 2: You want request.url instead of request.request_uri. This combines the protocol (usually http://) with the host, and request_uri to give you the full address