Featured

Factorial program in Ruby. ( A small and basic Interview question )

If you have an interview and if you comes under 3 years of experience or a fresher. You may face few basic interview question like Factorial, Fibonacci series, Amstrong etc.

Let’s see how we can write a factorial program in Ruby.

First of all What is a Factorial?

It is nothing but a product of an integer and all the integers below it.

For example

Factorial 5 (5!)   5 x 4 x 3 x 2 x 1 => 120

How we can achieve it in Ruby

We have so many ways to achieve this in Ruby. Let’s see the best one

def factorial(n)
if n <= 0
1
else
n * factorial(n-1)
end
end

Let’s see the output

1.9.2-p330 :008 > factorial(5)
=> 120

That’s it. We have so many other ways to achieve the factorial but the above one will give you the basic idea of the program in a recursive way.

Preview email instead of sending it in Development

In Rails generally we do use SMTP or Sendgrid for emails. To test the emails we are sending it to our emails and checking how the email format looks and how the attachments are working. Instead of sending the email we can do test using one gem called ” letter opener” . So, how can we use it in our rails application.

First we need to add the gem and run bundle install in our development environment.

gem “letter_opener”, :group => :development

In the application folder config/environments/development.rb add the following configuration

config.action_mailer.delivery_method = :letter_opener

Restart the application and you can see any email can pop-up in browser tab instead of sending it. That’s it.

Fibonacci in Ruby

Fibonacci is general and basic program in interviews. Some times even 5+ years candidate can not answer this question. It’s not a lack of technical knowledge but in real-time when working on several projects and getting more experience we may miss to brush up our basics.Sometimes this may lead to lose an opportunity in interviews when we prepare more and more deep in subject but forgot these basic programs. Once I got failed to answer this program when I have 4 years experience in Ruby but failed.

Fibonacci in Ruby, We can do it in many ways but here is one of the way.

``````
def fibonacci(k)
a=0
b=1
result = []
k.times do
temp = a
a=b
b=temp+a
result.push(b)
end
puts result
end
fibonacci(7)
``````

How to create a child records with has_one associations

We knew about rails associations and one of the association is has_one. If we have has_one association. What will be parent and child records looks?

Small example: We have two models i.e. User and Profile

class User
has_one :profile
end

class Profile
belongs_to :user
end

So, If we create a record profile of respective user . What it exactly happens , Lets see through rails console:

I am trying here to create a profile for user as normal which is having has_one association between user and profile models but in the below image you can see it throwing an error ” undefined method ‘new’ for nil:NilClass”. So , how can we create it ?

We can create it as follows. It is different to create a compare to other association relations. We have to use  create_<model_name> method. In our example create_profile. Lets see the below screenshot how we can create a profile.

you can find what all methods available in has_one association Methods in has_one

Difference between resource and resources in Rails routes

Have you ever observed the difference between resource and resources?
Do you know when to use resource instead of resources?Here I would like to explain based on my observations let’s take a
look.

As general we noticed that while using resource in the routes file the action we have are as follows

resource: new, create, edit, update, show, destroy

Here we found that the index action was missed. Yes While using resources we have index action but not in the resource.

Let’s see why?

the resource is a singular
resources is a plural

In some cases, we may have a resource that always lookup without an ID. Let’s assume we need to show current logged in User
details. So no need of ID as the current logged user is the key here.

Resources is used to handle any request on any record based on ID. While Resource will depend on the current record.

We also have a difference in defining a path in view pages to actions.

Hope this small explanation helps you

Simple Ruby code send mails

require ‘net/smtp’

message = <<MESSAGE_END
To: There mail id <yout@example.com>
This is a test mail to check ruby code is working for sending mails ?

MESSAGE_END

Net::SMTP.start(‘localhost’) do |smtp|
smtp.send_message message, ’email1@example.com’,
’email2@example.com’
puts “mail sent”
end

Fetch ipaddress and get location using ruby

require ‘rubygems’
require ‘geocoder’
require ‘socket’
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off reverse DNS resolution temporarily

UDPSocket.open do |s|
s.connect ‘64.233.187.99’, 1
end
ensure
Socket.do_not_reverse_lookup = orig
end

location.each do |lc|
puts lc.city
if lc.city == “”
puts “this ip is reserved not able to fetch details “
end
end

Install socket gem and require it in you code

require ‘socket’

// local_ip is custom method to fetch ip address of the system u connected to global through //internet
def local_ip
orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true  # turn off    reverse DNS resolution temporarily

UDPSocket.open do |s|
s.connect ‘64.233.187.99’, 1
end
ensure
Socket.do_not_reverse_lookup = orig
end

Mongoid in Ruby on Rails

Mongoid  is an Object-Document-Mapper (ODM) for MongoDB written in Ruby which works similar to ORM to other database in rails application.
Ruby developers who have been using Active Record or Data Mapper, while leveraging the power of MongoDB’s schemaless,performant document-based design, dynamic queries.

class Project
include Mongoid::Document
field :name, type: String
embeds_many :developers
end

class Developer
include Mongoid::Document
field :name, type: String
embedded_in :project
end

While using mondoDB in Rails application we need to include mongoid:Document in every model in our applications.

filed is the field name and the datatype we are specifying

embeds_many is nothing but has_many relationship In this way we can use mongoid in our rails application this is the simple exaplination about mongoid usage.