Friday, 21 August 2015

Setup EC2 instance and deploy using mina.

Amazon  EC2 :
System Update : - sudo apt-get update

===========RVM ============
sudo apt-get install curl
command curl -sSL https://rvm.io/mpapis.asc | gpg --import -
\curl -L https://get.rvm.io | bash -s stable
echo "source $HOME/.rvm/scripts/rvm" >> ~/.bash_profile
echo "source $HOME/.rvm/scripts/rvm" >> ~/.bashrc


Restart Required
type
rvm | head -n 1
rvm requirements
rvm install ruby-2.1.0 #... version of ruby used in your application
else rvm install 2.0.0
gem install bundler --no-ri --no-rdoc
sudo apt-get -y install curl git-core

============ rake===========
sudo apt-get install rake


==============Mysql===============
sudo apt-get update

sudo apt-get install mysql-server mysql-client


sudo apt-get install libmysqlclient-dev


==============Rmagick===============
sudo apt-get install imagemagick
sudo apt-get install libmagickwand-dev


==============Nokogiri===============
sudo apt-get install libxslt-dev libxml2-dev


=================Mina==========================
 Setup Mina for rails deployment Click
 For Nginx or unicorn configuration Click , this is tested application.

 Step 1: mina setup   #------ for setup all configuration file and for making all required directory.
Step 2: mina deploy on=production  #----on any environment 

Note: Make sure first your database configuration file will be correctly working.

 


Friday, 7 August 2015

When developing an application, it’s easy to just think about the happy path. The happy path is the flow through the application when everything works as expected.
The user enters the correct data, the request satisfies the business logic and any interaction with third party services or infrastructure happens without a hitch.
In reality, there are many more paths than the happy path.
Exceptions are a way of dealing with exceptional circumstances that will occur and they are a very important tool for controlling the execution flow of your application.
In today’s tutorial we will be looking at using Exceptions in our Ruby applications.

What is an Exception

An Exception is used to halt the execution of the application under a particular set of circumstances.
The Exception can then be “rescued” and either dealt with, or allowed to bubble up to the surface.
When an Exception is rescued, the problem can sometimes be resolved.
However, the majority of the time you would want to rescue the exception and provide a good error message to the user.
Exceptions can also be used stop execution if you think the user has malicious intent.

Using Exceptions in Ruby

An Exception is basically just a special type of Ruby object that when created will terminate the current application.
All Exceptions inherit from the standard Exception Ruby object.
To create new Exception you use the raise method:

def oh_noes
  raise "oh noes, something went wrong!!1"
end

oh_noes

The raise method accepts a message that can be used to help figure out what went wrong.
The code above would result in the following error:



exceptions.rb:2:in `oh_noes’: oh noes, something went wrong!!1 (RuntimeError) from exceptions.rb:5:in `



So as you can see, Ruby tells us:
  • The line in which the Exception was thrown exceptions.rb:2
  • The method name oh_noes
  • The error message something went wrong!!1
  • The type of Exception (RuntimeError)
  • And where the method was triggered from exceptions.rb:5

The different types of Exceptions

An important aspect of using Exceptions is using the correct Exception under the specific circumstances.
As you saw above, by default when you call the raise method, an instance of RuntimeError will be thrown.
However, Ruby has a number of other default Exceptions that should be used under the appropriate circumstances. You can see a list of these exceptions in the Exception documentation.
If you want to raise a specific type of error, you can pass it as the first argument to the raise method:

def oh_noes
  raise ArgumentError, "oh noes, something went wrong!!1"
end

This will raise an Exception of type ArgumentError which might be more appropriate if a method was accepting a specific type of argument in order to function correctly.


Rescuing an Exception

When an Exception is raised, you will often want to rescue the situation and take a different course of action or provide a more informative error for the user.
In order to do this, you can “rescue” the Exception:


def oh_noes
  puts "Before the Exception"
begin
  puts "Just before the Exception"
raise ArgumentError, "oh noes, something went wrong!!1"
  puts "Just after the Exception"
rescue
  puts "Rescuing the Exception"
end
  puts "After the Exception"
end

oh_noes

To rescue from an Exception you can wrap the Exception in an begin rescue end block.
The begin section is the processing that might trigger the Exception, and the rescue section is what you want to happen if something triggers the Exception.


Defining your own Exceptions

Ruby provides a number of standard Exceptions that allow you to signify the different exceptional circumstances an application can find itself in.
However, using Exceptions is much more powerful than just dealing with common application problems.
Exceptions allow you to expressively deal with “exceptional” circumstances, no matter what those circumstances are.
By defining your own Exceptions, you can write code that is very explicit when something goes wrong.
To define your own Exception, you can simply create a new class that inherits from one of the standard Ruby Exception classes:


class UserDoesNotHavePermission < StandardError 

end

In this example we have created a new UserDoesNotHavePermission Exception that should be used when the user is attempting to perform an action they do not have permission for. As you can see, the cause of the Exception is immediately obvious.
Now when writing you code, you can throw this specific Exception under that specific circumstance.
This is beneficial for two reasons.
Firstly, if another developer is consuming you code and they receive an instance of the this Exception, it is immediately obvious what went wrong.
Secondly, when testing your code, you can very easily assert that the code failed for the correct reason by ensuring that the correct Exception is raised, and not just a StandardError which could of be raised for any number of reasons.

A couple of weeks ago we looked at using Modules (Creating and using Modules in Ruby). Modules are also a really good way of grouping Exceptions:



module UserPermissions
  class PermissionError < RuntimeError 

  end 
  class UserDoesNotHavePermission < PermissionError 
  end 
  class UserDoesNotBelongToAccount < PermissionError 
  end 
  class UserIsNotAnAdmin < PermissionError 
 end 
end

In this example we’ve defined a new UserPermissions module that has 4 Exceptions.
To handle a specific exception, you can rescue that particular Exception:


UserPermissions::UserIsNotAnAdmin
However, you can also rescue any of the Exceptions from this module by using the generic PermissionError Exception:


UserPermissions::PermissionError

For More Detail: Ruby Exception 

Conclusion

Exceptions are a beautiful way of dealing with problems within your code. There will be inevitably any number of different paths and situations your code can find itself in, and so using Exceptions is an expressive and explicit way to deal with these different circumstances.
Exceptions make your code easier to understand and deal with problems. When another developer is using your code, you can make it really easy for them to know what went wrong by providing granular Exceptions that can be dealt with in different ways.
It’s also much easier to test code and assert that the code failed for the correct reason. When you create explicit Exceptions you can assert that what you think happened really did happen, rather than simply listening out for generic Exceptions.

Friday, 31 July 2015

AWS EC2 Machine SSH with local Ubuntu Machine without password

After creating AWS EC2 Ubuntu Machine over server they provide you .pem file for login on EC2 machine. When first time I create a machine on AWS EC2 then I face a problem I was not able to ssh AWS EC2 machine by my local Ubuntu system. After google I found a way to ssh with local Ubuntu system. You also able to add more than one user on your AWS EC2 Machine.

First you must have a AWS EC2 Machine over server.

For creating AWS EC2 Machine instance Click on AWS EC2 Machine

Now !

1. ssh using your .pem file something like this.

ssh -2 -i ~/Downloads/blogapp.pem ubuntu@ec2-12-345-67-891.compute-1.amazonaws.com


2. After successful login you copy your local Ubuntu  id_rsa public key and paste to this file.

ubuntu@ip-172-31-26-53:~$ nano ~/.ssh/authorized_keys 



-----------------------------------------------------------------------------------------------------------------------------------
You Also ssh without password in local Machine


1. ssh-keygen -t rsa
Press enter for each line
2. cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys
3. chmod og-wx ~/.ssh/authorized_keys 



Note: You also add multiple User on Your local and AWS EC2 Machine.

Prerequisite requirement:
 sudo apt-get install openssh-client 

 sudo apt-get install openssh-server

Friday, 24 July 2015

Diffrence between after_create and after_commite in Rails

They are not interchangeable. The key difference is when the callback runs. In the case of after_create this will always be before the call to save (or create) returns.

Rails wraps every save inside a transaction and the before/after create callbacks run inside that transaction (a consequence of this is that if an exception is raised in an after_create the save will be rolled back). With after_commit your code doesn't run until after the outermost transaction was committed. This could be the transaction rails created or one created by you (for example if you wanted to make several changes inside a single transaction).

Example:
after_create only works once - just after the record is first created.
after_save works every time you save the object - even if you're just updating it many years later
So if you want to do this email operation only just the once (and then never again) then use after_create
If you want to do it every time the object is saved, then do it in after_save

The after_commit and after_rollback callbacks are guaranteed to be called for all models created, updated, or destroyed within a transaction block. If any exceptions are raised within one of these callbacks, they will be ignored so that they don’t interfere with the other callbacks. As such, if your callback code could raise an exception, you’ll need to rescue it and handle it appropriately within the callback.

For Example : Example of After commit
For more detail: rails transaction

Friday, 17 July 2015

Private and Protected Method In Ruby

Public, Protected and Private refer to the accessibility of those methods.

By default, all methods are Public. If you do not specify the accessibility of a method, it will be Public.
Protected and Private methods are not publicly accessible and so when you have an instance of an Object you will not be able to call those methods.

Protected and Private methods also have differences around how you can use them within the context of an Object.


Private Methods


Both Private and Protected methods are not accessible from outside of the object as they are used internally to the object.
Another important aspect of good object-oriented design is that the consumer of an object should not have to know how that object is implemented.
Private methods and Protected methods, whilst both being inaccessible outside of the scope of the object, have a subtle difference.
I think it’s easier to understand Private methods, and so we’ll start here.
To define a private method you use the private keyword. private is not actually a keyword, it’s a method, but for all intents and purposes, it’s easier to just think of it as a keyword.
For example, we might have the following method in our Product class:


class Product
attr_accessor :name, :quantity

def initialize(name)
  @name = name
  @quantity = 1
end

def increment
  @quantity += 1
end

private
  def stock_count
    100
  end
end


To signify that the stock_count method is private we can place it under the private heading.
There is actually a couple of different ways to define private methods, but I think the method above is the most common.
Now when we have an instance of the Product object, we can’t call the stock_count method because it is private:



milk = Product.new("Milk")
=> #

milk.stock_count
NoMethodError: private method 'stock_count' called for #




In order to call the stock_count method, you need to be within the scope of the object:

class Product
attr_accessor :name, :quantity

def initialize(name)
  @name = name
  @quantity = 1

puts "There are #{stock_count} in stock"
end

def increment
  @quantity += 1
end

private
  def stock_count
    100
  end
end


Now when we instantiate a new instance of the object, we will see the stock count:

milk = Product.new("Milk")
  There are 100 in stock
=> #



So the only way to call a Private method is to do so within the context of the object instance.
However, an interesting thing to note about Private Ruby methods is the fact that a Private method cannot be called with an explicit receiver, even if that receiver is itself.
When I say “receiver”, I mean the object that the method is being called from.
So for example:


class Product
  attr_accessor :name, :quantity

def initialize(name)
  @name = name
  @quantity = 1

puts "There are #{self.stock_count} in stock"
end

private
  def stock_count
    100
  end
end


In this example I’ve modified the initialize method to use self.stock_count. In this case, self refers to the current object.
However, when you attempt to create a new instance of Product you will get an error:

milk = Product.new("milk")
NoMethodError: private method `stock_count’ called for #


So you can only call Private methods from the current context of the object, and you can’t call Private methods with a receiver, even if that receiver is self.

 Protected Methods 

Finally we have Protected methods. A Protected method is not accessible from outside of the context of the object, but it is accessible from inside the context of another object of the same type.
For example, imagine we have the following sku method on the Product class:

class Product
attr_accessor :name, :quantity

def initialize(name)
  @name = name
  @quantity = 1

puts "The SKU is #{sku}"
end

protected
  def sku
   name.crypt("yo")
  end
end


In this example we are generating a SKU from the product’s name.
As with the Private method example from earlier, this method is not accessible outside the context of the object:

milk = Product.new("Milk")
The SKU is yo.B6xygWtQ1w
=> #<Product:0x007fd7a2184058 @name="Milk", @quantity=1>
milk.sku
NoMethodError: protected method 'sku' called for #<Product:0x007fd7a2184058 @name="Milk", @quantity=1>
However, if you call the method with self it will work:

class Product
attr_accessor :name, :quantity

def initialize(name)
  @name = name
  @quantity = 1

puts "The SKU is #{self.sku}"
end

protected
  def sku
   name.crypt("yo")
  end
end


So a Protected class method can be called within the context of an object of the same type.
This means you can call Protected class methods of other objects inside an object of the same type. For example:


class Product
attr_accessor :name, :quantity

def initialize(name)
@name = name
@quantity = 1
end

def ==(other)
  self.sku == other.sku
 end

protected
  def sku
    name.crypt("yo")
  end
end

In this class we’ve implement the == method to assert equality between two objects. This method accepts another Product object and will call the Protected sku method.
If the two Product objects have the same name, they will be considered equal:


milk1 = Product.new("Milk")
=> #

milk2 = Product.new("Milk")
=> #

bread = Product.new("Bread")
=> #

milk1 == bread
=> false

milk1 == milk2
yo
=> true


So the important thing to note here is, you can call Protected methods inside the context of an object of the same type.

Conclusion  

The differences between Public, Private and Protected methods can seem confusing at first, particularly the differences between Private and Protected methods.
Writing a clean and easy to use public interface for your objects is a very important part of the design process. The public API will say a lot about the object and how it should be used. It’s important to take care and ensure you make good choices when deciding on method names and what methods should be public.

The choice between Private and Protected will come down to how you intend your object to be used.
As with just about everything else in programming, learning via experience is really the only way to progress. If today’s tutorial seemed like a lot to take in, don’t worry about it. As long as you keep exploring, you will eventually find the way.

:::Happy hacker ;) 

Friday, 10 July 2015

Bullet Gem for Ruby on Rails

In rails some time it's hard optimized performance of rails application but if we use some helping gem for optimized the rails application then it's simple and easy. There are so many gems for notify the process  and showing internal working structure One of my favorite gem is Bullet   this gem very use full when we want to solve N+1 problem in any rails application and want to speed up own application.

N+1 Problem :
    

First Get a list of things
@courses = current_user.courses

Iterate over it, getting something for each thing.
<% @courses.each do |course| %>
  <%= course.name %>
  <%= course.teacher.name %>
<% end %>

Fix: -

@courses = current_user.includes(:teacher)

Basically Bullet gem help to find out where we want includes methods to resolving n+1 problem in rails application.

Here some simple step to using Bullet gem inside rails application.

1. Adding Gem in your Gemfile

gem 'bullet'

2. Now ! run bundle install to install bullet gem.
3. Adding some configuration for bullet gem in development.rb file .


cofig.cache_classes = true

config.after_initialize do
  Bullet.enable = true
  Bullet.alert = ENV['BULLETS_ALERTS']
  Bullet.bullet_logger = true
  Bullet.console = true
  Bullet.rails_logger = true
end


4. Now run the rails application

BULLETS_ALERTS=true rails s
--------------------------------------------------------------------------------------------------------------------------

When we hit the application and if any N+1 and require counter Cache problem detect the bullet gem show pop-up and notify with detail where problem detect and also how to re-solve it. It is very help full gem for increase performance of any rails application.

 

Friday, 3 July 2015

How to Use Beautified_url Gem in Ruby on Rails Application

Beautified Url Basic tool which provides feature of generating tokens which can be used in url for identifying resource(uniquely of uniquely within a scope) instead of :id. Just add another field which starts with _bu_ of one or many existing fields to make it all happen. Example: For a blog post, if you have a 'title' field and want to beautify and use it .

Simple way to implement ..
1. Adding gem  in your Gem-file.

 gem 'beautified_url', '~> 0.0.2'
 

2. Now you have to create a migration(adding a column  for _bu_ url ) on model for beautified Url.
the name of column is start with _bu_ .


class AddingBfColumnInUsers < ActiveRecord::Migration

 def change 
   add_column :users, :_bu_name, :string, after: 'full_name' 
 end 
end
---------------------------------------------------------------
class AddingBfColumnInProjects < ActiveRecord::Migration

 def change
  add_column :projects, :_bu_name, :string, after: 'name' 
 end 
end

3. Now last step is create routes for the resources

get ':_bu_full_name/:_bu_name', to: 'projects#show', as: :show_project
get ':_bu_full_name/:_bu_name/edit', to: 'projects#edit' , as: :edit_project


NOTE : If prams not found then You have also pass _bu_name and _full_name (user full name ) as prams through model by overriding to_prams default methods.

class Project < ActiveRecord::Base 

  def to_param 
    _bu_name.to_s 
  end 
end 




Salesforce CRM vs. Zoho: A Comparative Analysis

Introduction: Selecting the right customer relationship management (CRM) software is crucial for businesses seeking to streamline their sal...