Destructive method in ruby

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.

example
myval = [‘phy’, ‘chem’, ‘bio’]
#myval is of type Array.

myval.reverse returns [“bio”, “chem”, “phy”] but the dont alter the object

p myval

#outputs:
#[‘phy’, ‘chem’, ‘bio’]

But
myval.reverse!
# this method altered the object.

p myval

#outputs:
#[“bio”, “chem”, “phy”]

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

Error:- ActionView::Template::Errror (application.css isn’t precompiled)

Rails assumes that you have your files pre-compiled in the production environment.

if want to compile at runtime set as the following

in the file config/environments/production.rb

config.assets.compile = true

for better performance in production want to set config.assets.compile to false in production.rb

You can precompile with this rake task:

bundle exec rake assets:precompile

Explore more about .nil? .empty? .blank? .present? in Ruby on Rails

nil?, empty? and blank? and .present? are little bit confusing.

We as a Developer needs to be careful in using them and it is better that we digest the details before using it.

.nil?

  • It is Ruby method
  • It can be used on any object and is true if the object is nil.
  • “Only the object nil responds true to nil?” – RailsAPI

In Ruby, all classes inherit from the Object class. nil? is a method of Object; therefore, unless explicitly overridden, all classes have access to nil?. To better understand how Ruby expresses the concept of a non existent object, we need to look at its pseudo-variable nil. The same idea in other languages is often mapped to the primitive type, null or NULL. Depending on the language, NULL may point to nothing at all. Ruby differs here, in that, nil references an actual class called NilClass which exposes methods. This is why it’s possible to do seemingly illogical things like:

nil.nil?    => true
When calling on an object that is non existent, invalid or explicitly set to nil, an instance of the singleton NilClass is returned.

A few examples will illustrate how this works.

posts= {:name=> “my post”, :description=> “my description”}

posts[:name]   => nil
posts[:name].class  => NilClass
posts[:name].nil? => true
posts[:description].nil? => false

my_test_var = nil
my_test_var .nil? => true

[].nil? => false

“”.nil? => false

0.nil? => false

false.nil? => false

empty?

Unlike nil?, empty? is only available on some Ruby objects. String, Hash and Array are a few of the classes that implement it. When calling empty? the receiving object is being checked to see if it possesses a non-nil value or values. empty? (at least for the mentioned classes) returns either true or false.

  • It is Ruby method
  • can be used on strings, arrays and hashes and returns true if:

String length == 0
Array length == 0
Hash length == 0

  • Running .empty? on something that is nil will throw a NoMethodError

[“name”, “title”, “description”].empty? => false

[“”].empty? => false

[].empty? => true

{}.empty?=> true

“”.empty?=> true

0.empty? => NoMethodError: undefined method `empty?’ for 0:Fixnum

my_test_var2 = nil
my_test_var2 .empty? = > NoMethodError: undefined method `empty?’ for nil:NilClass
The last example above clearly illustrates why one would get unexpected results when trying to do things like this:

dog = {:name => “Beauregard”}
puts “What kind?” if dog[:breed].empty?
=> NoMethodError: undefined method `empty?’ for nil:NilClass

# Use nil? instead.
puts “What kind?” if dog[:breed].nil?
=> What kind?

.blank?

  • It is Rails method
  • operate on any object as well as work like .empty? on strings, arrays and hashes.
  • It also evaluates true on strings which are non-empty but contain only whitespace:

“An object is blank if it‘s false, empty, or a whitespace string.
For example, “”, ” “, nil, [], and {} are blank.”

For instance, I often use blank? when operating on form field values that are considered optional by a model. Going back to the dog hash, we can see how blank? simplifies testing for values.

nil.blank? = true
[].blank? = true
{}.blank? = true
“”.blank? = true
5.blank? == false
dog = {:name => “Beauregard”}
puts “What kind?” if dog[:breed].blank?
=> What kind?

dog = {:name => “Beauregard”, :breed => “”}
puts “What kind?” if dog[:breed].blank?
=> What kind?
” “.blank? == true” “.empty? == false

present?


Quick tip: !obj.blank? == obj.present?
activesupport/lib/active_support/core_ext/object/blank.rb, line 17 # (Ruby 1.9)

def present?
!blank?
end

 

Ruby on Rails Interview Questions and Answers

Hey guys, hope you’re having a fine day. Today, my post will be to help answer some of the most difficult technical interview questions; because, interviews can always be stressful even for job seeker who have attended countless interviews. I believe the best way to reduce the stress is to be prepared.

Here are some of the most frequently asked questions and how to answer them confidently.

What is agile development

A:Agile methodology is anadaptaive methodology, its people
oriented.
Here are some of the other characteristices of the Agile
methodology.
1. Delivery frequently.
2. Good ROI for client.
3. Test frequently.
4. Collaborative approach.
Agile methodology is on daily basis report. How much work we have completed on that day and how much work is still pending…it gives the clear picture but the req are not defined beforehanditself completely.. req will be changing….

Why Ruby on Rails?

A: There are lot of advantages of using Ruby on Rails(ROR)
1. DRY Principal
2. Convention over Configuration
3. Gems and Plugins
4. Scaffolding
5. Pure OOP Concept

What is MVC? and how it Works?
A: MVC tends for Model-View-Controller, used by many languages like PHP, Perl, Python etc. The flow goes like below image

mvc1

 

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.

What is ORM in Rails?
A: 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.

What is Ruby Gems?
A. Ruby Gem is a software package, commonly called a “gem”. Gem contains a packaged Ruby application or library. The Ruby Gems software itself allows you to easily download, install and manipulate gems on your system.

What is Gemfile and Gemfile.lock?
A. The Gemfile is where you specify which gems you want to use, and lets you specify which versions. The Gemfile.lock file is where Bundler records the exact versions that were installed. This way, when the same library/project is loaded on another machine, running bundle install will look at the Gemfile.lock and install the exact same versions, rather than just using the Gemfile and installing the most recent versions. (Running different versions on different machines could lead to broken tests, etc.) You shouldn’t ever have to directly edit the lock file.
Get more Explanations on Gem file here.

What is Active record

A-There are many reasons why Active Record is the smart choice
Simplified configuration and default assumptions (Convention over Configuration).
Associations among objects.
Automated mapping b/w tables and classes and b/w columns and attributes.
Data Validations.
Callbacks
Inheritance hierarchies.
Direct manipulation of data as well as schema objects.
Database abstraction through adapters.
Logging support.
Migration support.
Active Record integrated in other emerging frameworks like Merb.

How you run your Rails application without creating databases?
A. You can run your application by uncommenting the line in environment.rb
path=> rootpath conf/environment.rb
config.frameworks- = [action_web_service, :action_mailer, :active_record

What are the servers supported by ruby on rails?
A. Ruby Supports a number of Rails servers (Mongrel, WEBRICK, PHUSION, Passenger, etc..depending on the specific platforms).
For each Rails application project, RubyMine provides default Rails run/debug configurations for the production and development environments.

What is the difference between a plugin and a gem?
A. 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.

What is restful in rails

A.Stands for REpresentational State Transfer

RESTfulRails

What is passanger
A. Easy and robust deployment of ruby on rails app on appache and ngix webservers
passenger is an intermediate to run the ruby language in linux server

 What is request.xhr?
A: A request.xhr tells the controller that the new Ajax request has come, It always return TRUE or FALSE

What is the Difference between Static and Dynamic Scaffolding?
A: 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.

What is Session and Cookies?
A: 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] = “srikant” it remains when the browser is not closed

What is the difference between form_for and form_tag

A. form_tag and form_for both are used to submit the form and it’s elements.
The main difference between these two is the way of managing objects related to that particular model is different.
form_for
——-
We should use “form_for” tag for a specific model
It performs the “standard http post” which is having fields related to active record (model) objects

form_tag:
—–
It creates a form as a normal form. form_tag also performs the “standard http post” without any model backed and has normal fields. This is mainly used when specific data need to be submitted via form.
It just creates a form tag and it is best used for non-model forms.

Example:

<% form_tag ‘/articles’ do -%>
<%= text_field_tag “article”, “firstname” %>
<% end -%>

Difference between ruby 1.8.7 and 1.9.2

A.Ruby 1.9 – Major Features

Performance
Threads/Fibers
Encoding/Unicode
gems is (mostly) built-in now
if statements do not introduce scope in Ruby.

-{“a”,”b”} No Longer Supported
-Array.to_s Now Contains Punctuation
-Colon No Longer Valid In When Statements

What are the engines in mysql
Ans: In previous versions of MySQL, MyISAM was the default storage engine. In our experience, most users never changed the default settings. With MySQL 5.5, InnoDB becomes the default storage engine.

What is the difference between include and extend
A.include makes the module’s methods available to the instance of a class, while
extend makes these methods available to the class itself.

http://lesseverything.com/blog/archives/2012/08/02/the-difference-between-include-and-extend-in-ruby/
When you use include, the module’s methods are added to the instances of the class. The log method is:

Not available at the class level
Available at the instance level
Not available at the class level again

When you use extend, the module’s methods are added to the class itself. The log method is:

Available at the class level.
Not available at the instance level.
Available at the class level.
Reference:
http://ionrails.com/2009/09/19/ruby_require-vs-load-vs-include-vs-extend/
http://rubyquicktips.com/post/1133877859/include-vs-extend

What is the difference between lambada and proc

A.proc and Lambda are used to create code blocks. After creating them, we can pass them around our code, just like variables.

How to call method dynamically

A.[“foo”, “bar”].each do |method|
MyClass.send(method)
end

How to create a method dynamically

A.class Message
[:hello, :goodbye].each do |method_name|
define_method method_name do |arg|
“#{method_name} #{arg}”
end
end
end

#irb
Message.instance_methods false #=> [:hello, :goodbye]
Message.new.hello ’emre’ #=> “hello emre”
Message.new.goodbye ’emre’ #=> “goodbye emre”

How to use Nested routes in ROR

The easiest way to create a nested route, is to use the :has_many keyword like that:

# /config/routes.rb
map.resources :projects, :has_many => :tasks

# and the correspondent task resource
map.resources :tasks

Adding the second routes, that defines a RESTful route to :tasks, depends if you would like to allow an access to the Task resource, without the project context, this is not a must.
Reference
http://pandejo.blogspot.in/2009/03/rails-nested-resources-tutorial.html

What things we can define in the model?
A: 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

How many Types of Relationships does a Model has?
A: * (1) has_one
* (2) belongs_to
* (3) has_many
* (4) has_many :through

What is asset pipeline
A.asset pipeline which enables proper organization of CSS and JavaScript

What is observer in rails

A:Observer classes respond to life cycle callbacks to implement trigger-like behavior outside the original class.

Rails observers are sweet, You can observe multiple models within a single observer

First, you need to generate your observer:

command – rails g observer Auditor

-observer classes are usually stored in app/models with the naming convention of app/models/audit_observer.rb.

In order to activate an observer, list it in the config.active_record.observers configuration setting in your config/application.rb file.

config.active_record.observers = :comment_observer, :signup_observer
Observers will not be invoked unless you define these in your application configuration.
Reference: http://apidock.com/rails/ActiveRecord/Observer
What is rails sweeper
A:http://dev.mensfeld.pl/2011/07/using-rails-sweepers-outside-controllers/
One sweeper can observe many Models, and any controller can have multiple sweepers.

Difference between -%> and %> in rails
A:The extra dash makes ERB not output the newline after the closing tag. There’s no difference in your example, but if you have something like this:

<% if true -%>
Hi
<% end -%>

It’ll produce:

Hi

and not this:

Hi

Difference between render and redirect?
A:
Redirect is a method that is used to issue the error message in case the page is not found or it issues a 302 to the browser. Whereas, render is a method used to create the content.

-Redirect is used to tell the browser to issue a new request. Whereas, render only works in case the controller is being set up properly with the variables that needs to be rendered.

-Redirect is used when the user needs to redirect its response to some other page or URL. Whereas, render method renders a page and generate a code of 200.

-Redirect is used as:
redirect_to: controller => ‘users’, :action => ‘new’

-Render is used as:
render: partial
render: new -> this will call the template named as new.rhtml without the need of redirecting it to the new action.

What is the use of rake db:reset

A.db:create——- creates the database for the current env
db:create:all ———creates the databases for all envs
db:drop ———-drops the database for the current env
db:drop:all ———-drops the databases for all envs
db:migrate ———-runs migrations for the current env that have not run yet
db:migrate:up ——–runs one specific migration
db:migrate:down ——-rolls back one specific migration
db:migrate:status —–shows current migration status
db:migrate:rollback —rolls back the last migration
db:forward ————advances the current schema version to the next one
db:seed (only) ———runs the db/seed.rb file
db:schema:load ————loads the schema into the current env’s database
db:schema:dump ———dumps the current env’s schema (and seems to create the db aswell)

db:setup ————-runs db:schema:load, db:seed

db:reset ———-runs db:drop db:setup
db:migrate:redo ———runs (db:migrate:down db:migrate:up) or (db:migrate:rollback db:migrate:migrate) depending on the specified migration
db:migrate:reset ——runs db:drop db:create db:migrate

What is eagerloading
A.-One way to improve performance is to reduce the number of database queries through eager loading.
-You can know where we need eager loading through “Bullet’ Gem

How to use sql db or mysql db. without defining it in the database.yml
A.

What are helpers and how to use helpers in ROR?
A. 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.

What is Active Record?
A. Active Record are like Object Relational Mapping(ORM), where classes are mapped to table and objects are mapped to colums in the table

Ruby Supports Single Inheritence/Multiple Inheritence or Both?
A. Ruby Supports only Single Inheritnece

How many types of callbacks available in ROR?
A. * (-) 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

How to use two database into a Single Application?

A. http://magicmodels.rubyforge.org/magic_multi_connections/, According to this link : ActiveRecord models are allowed one connection to a database at a time, per class. Ruby on Rails sets up the default connection based on your database.yml configuration to automatically select development, test or production.
But, what if you want to access two or more databases – have 2+ connections open – at the same time. ActiveRecord requires that you subclass ActiveRecord::Base.
That prevents you doing migrations from one database to another. It prevents you using one set of model classes on two or more databases with the same schema.
Magic Multi-Connections allows you to write your models once, and use them for multiple Rails databases at the same time. How? Using magical namespacing.

To do this :
[A] sudo gem install magic_multi_connections
[B] require ‘magic_multi_connections’
Add the following to the bottom of your environment.rb file
You can also find examples on this link : http://magicmodels.rubyforge.org/magic_multi_connections/

“Updated Set of Questions for Rails 3”

What is the difference between the Rails version 2 and 3?
A. * (1) Introduction of bundler (New way to manage your gem dependencies)
* (2) Gemfile and Gemfile.lock (Where all your gem dependencies lies, instead of environment.rb)
* (3) A new .rb file in config/ folder, named as application.rb (Which has everything that previously environment.rb had)
* (4) Change in SQL Structure: Model.where(:activated => true)
* (5) All the mailer script will now be in app/mailers folder, earlier we kept inside app/models.
* (6) Rails3-UJS support. for links and forms to work as AJAX, instead of writing complex lines of code, we write :remote => true
* (7) HTML 5 support.
* (8) Changes in the model based validation syntax: validates :name, :presence => true
* (9) Ability to install windows/ruby/jruby/development/production specific gems to Gemfile.
group :production do
gem ‘will_paginate’
end

What is bundler?
A: Bundler is a new concept introduced in Rails3, 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.

What is the Newest approach for find(:all) in Rails 3?
A: Model.where(:activated => true)

Ruby Interview Questions :

What are the variable in ruby

A.1 Local Variables – foobar
2 Instance Variables – @foobar
3 Class Variables – @@foobar
4 Global Variables – $foobar
——–
Name Begins With Variable Scope
$ A global variable
@ An instance variable
[a-z] or _ A local variable
[A-Z] A constant
@@ A class variable

Difference between “and” and && in Ruby?
A.and is the same as && but with lower precedence.

Difference between method overloading and method overwriting

A.def: In Method Overloading, Methods of the same class shares the same name but each method must have different number of parameters or parameters having different types and order.

Method Overloading means more than one method shares the same name in the class but having different signature.
In Method Overloading, methods must have different signature.
Method Overloading does not require more than one class for overloading.

Def:In Method Overriding, sub class have the same method with same name and exactly the same number and type of parameters and same return type as a super class.

Method Overriding means method of base class is re-defined in the derived class having same signature.
In Method Overriding, methods must have same signature.
Method Overriding requires at least two classes for overriding.

What is the Notation used for denoting class variables in Ruby?
A:We can know a variable as “Class variable’s” if its preceeded by @@ symbols.

What is the use of Destructive Method?
A: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.

What is the use of load and require in Ruby?
A:The require() method is quite similar to load(), but it’s meant for a different purpose.
You use load() to execute code, and you use require() to import libraries.

What is the use of Global Variable in Ruby?
A:Syntatically, a global variable is a variable whose name begins with $
Global variables in Ruby are accessible from anywhere in the Ruby program, regardless of where they are declared.
$welcome = “Welcome to Ruby Essentials”

How does nil and false differ?
A:nil cannot be a value, where as a false can be a value
A method returns true or false in case of a predicate, other wise nil is returned.
false is a boolean data type, where as nil is not.
nil is an object for NilClass, where as false is an object of for FalseClass

What is the diffence betweet symbol and string
A. Symbols have two nice properties compared to strings which can save you memory and CPU time
The difference remains in the object_id, memory and process time for both of them when used together at one time
Strings are considered as mutable objects. Whereas, symbols, belongs to the category of immutable
Strings objects are mutable so that it takes only the assignments to change the object information. Whereas, information of, immutable objects gets overwritten

How to use super key word

A.Ruby uses the super keyword to call the superclass implementation of the current method.
Within the body of a method, calls to super acts just like a call to that original method.
The search for a method body starts in the superclass of the object that was found to contain the original method.
def url=(addr)
super (addr.blank? || addr.starts_with?(‘http’)) ? addr : http://#{addr}
end

How is visibility of methods change in Ruby?

What is a Class Instance Variable

What are the rules and conventions to be followed in Ruby for naming a method?

How is class method defined in Ruby?

What are the Operators available in Ruby?

What are the looping structure available in Ruby?

What is the scope of local variable?

What are the OOP supported by Ruby?

If Ruby over PHP, Why?

Garbage collection in Ruby?

Environment Variables in Ruby?

What are Float, Dig and Max?
Ans.Float class is used whenever the function changes constantly. It acts as a sub class of numeric. They represent real characters by making use of the native architecture of the double precision floating point.
Max is used whenever there is a huge need of Float.
Dig is used whenever you want to represent a float in decimal digits.
What is Ruby Code blocks?

What kind of conditions ruby support?

Difference between puts and print
Ans.puts adds a newline to the end of the output. print does not.

Is there any technology apart from agile which we can use?

What are the servers supported by ruby on rails application?

Passenger running on Apache. Easy to set up, low memory usage, and well supported.
nginx with puma(it is a multi-threaded high performance webserver written in Ruby).

What is Meta-programming? How you are using it inside your rails application?

What is has_many?
Ans. It is a way of defining relationships among models. Correct, and Do you guys really know has_many is also an example of Meta-programming? Wondering, How?

What is TDD and BDD?
A: Test-Driven-Development and Behavior-Driven-Development

What is rspec, cucumber and Watir? And what it has to do with TDD and BDD?

What is the difference between ‘&&’ and ‘||’ operators?

A. “&&” has higher precedence than “||” like in most other mainstream languages; but “or” and “and” in ruby have the same(!) precedence level!
so if you write
(func1 || func2 && func3), it’s (func1 || (func2 && func3))
but
(func1 or func2 and func3) is interpreted as ((func1 or func2) and func3)
because of shorcircuiting, if func1 is true, both func2 and func3 won’t be called at all in the first example
but in the second example func3 WILL be called!
this difference is subtile enough that I really do not recommend newbies to use “and” and “or” in ruby at all.

What is the Purpose of “!” and “?” at the end of method names?
A. It’s “just sugarcoating” for readability, but they do have common meanings:
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”, but if number.zero just looks weird.
In your example, name.reverse evaluates to a reversed string, but only after the name.reverse! line does the name variable actually contain the reversed name. name.is_binary_data? looks like “is name binary data?”.

Just remember it in simple
In Ruby the ? means that the method is going to return a boolean and the ! modifies the object it was called on. They are there to improve readability when looking at the code.

How can you list all routes for an application?
A) By writing rake routes in the terminal we can list out all routes in an application.

What is rake?
A) rake is command line utility of rails. “Rake is Ruby Make, a standalone Ruby utility that replaces the Unix utility ‘make’, and uses a ‘Rakefile’ and .rake files to build up a list of tasks. In Rails, Rake is used for common administration tasks, especially sophisticated ones that build off of each other.”

Putting in simple word : “rake will execute different tasks(basically a set of ruby code) specified in any file with .rake extension from comandline.”

What are the differences between MongoDB and Redis?

A) Redis is a key value store while mongoDB is a document store.
  1.Data model
MongoDB
Document oriented, JSON-like. Each document has unique key within a collection. Documents are heterogenous.
Redis
Key-value, values are:

  • Lists of strings
  • Sets of strings (collections of non-repeating unsorted elements)
  • Sorted sets of strings (collections of non-repeating elements ordered by a floating-point number called score)
  • Hashes where keys are strings and values are either strings or integers After Wikipedia.

   2.Storage
MongoDB
Disk, memory-mapped files, index should fit in RAM.
Redis
Typically in-memory.
3.Querying
MongoDB
By key, by any value in document (indexing possible), Map/Reduce.
Redis
By key.

What are the new features of Rails4?
A)
1. Ruby Versions
2. ‘Gemfile’
3. ‘Threadsafe’ by Default
4. No More vendor/plugins
5. New Testing Directories
6. Strong Parameters
7. Renamed Callback
10. Queuing system
13. Cache Digests (Russian Doll Caching)
14. Turbolinks

More Questions and Answers of this will be published very soon 🙂 

Make your Rails Code Better using “Metric_fu”

Metric_fu is a set of rake tasks and compilation of several different tools that provide reports that show which parts of your code might need extra work . It uses Saikuro, Flog, Flay, Rcov, Reek, Roodi, Subversion, Git, and Rails built-in stats task to create a series of reports.

Rcov – Measures test coverage
Flog – Measures code complexity
Saikuro – Measures cyclomatic complexity
Flay – Finds duplication (both copy/paste and structural)
Reek – Spots code smells
Roodi – Finds lots of general problems
Churn – Identifies files that change too often
Rails best practices– Code matric tool
Cane– Code quality threshold violations
HotSpot– Meta analysis of your metrics to find hotspots in the code

Step#1

Add the gem in your gem file

gem “metric_fu”

Then run “bundle install”

Metric_fu will install several other dependencies unless they are already present. These include Flay, Flog, Rcov, Reek, Facets and Roodi. These are the tools that Metric_fu uses to generate its reports

Then, run the following command for generating the metrics

rake metrics:all

It will generate a matrics of your code in the temp/matric_fu folder, it uses a bunch of open source project to give all this to you

Benefits

  • You can major the complexity
  • Creates a “hit list” of your most complex method
  • It helps you to prioritize
  • Make you reveal on unknown problems like bugs and hidden complexity
  • Examine the worst offenders
  • Refactoring complex methods yields many benefits like Smaller, easier to understand methods and Finding bugs

Problem

  • We are aware of unknown complexity
  • Our code will get worse if it is not getting better

Conclusion

Code analysis isn’t an exact science and none of the tools shown are perfect in themselves, so they should all be used as an aid to help you find the areas of your code that might need some work not as an absolute instruction that you must refactor a part of your application.Image

 

Twitter Bootstrap for Rails 3

Bootstrap is a toolkit from Twitter designed to kickstart development of webapps and sites. It includes base CSS and HTML for typography, forms, buttons, tables, grids, navigation, and more

Step-1

Add gems inside asset group in your Gemfile

group :assets do
    gem ‘therubyracer’, ‘0.10.2’, :platforms => :ruby
    gem ‘libv8’, ‘3.3.10.4’
    gem ‘less-rails’

    gem ‘twitter-bootstrap-rails’
end

Step-2

bundle install

Step-3

rails generate bootstrap:install less

Step – 4

Generating layouts and views

rails g bootstrap:layout [LAYOUT_NAME] [*fixed or fluid]

example
rails g bootstrap:layout application fluid

Step-5

To add theme in all files of a resource (generates Twitter Bootstrap compatible scaffold views.)

rails g bootstrap:themed [RESOURCE_NAME]

 

Example:

rails g scaffold Post title:string description:text
rake db:migrate
rails g bootstrap:themed Posts

 

 

‘rails’ is not recognized as an internal or external command

This message means that Rails cannot be found. This might be due to the fact that you haven’t installed Rails or it may be due to the fact that the path to Rails cannot be found.

This might be the conflict of ruby of ruby path not set properly

Uninstall and Re-Install the ruby

Remove all version of rails

Then, run the gem from the system prompt, you should enter:

gem install rails –include-dependencies

Alternatively, you can download and install rails from the Ruby On Rails web site:

http://www.rubyonrails.org/

To make sure that Rails is installed, go to the system prompt and enter:

rails