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 




Friday, 26 June 2015

Faye Web Socket in Rails

Faye is  general-purpose web-socket it's also provide 2-way communication for client side ( user ) or server side. It is very use-full for sending notification on a given condition without reloading the whole page in browser and also help full for showing progress bar on run time server response simple way to implement this gem into your rails application.
Faye is working on multiple web server like

I am using thin web-server for my application to show notification.

1. First you add this line into you Gemfile 
--------------------------------------------------------

gem 'faye'
gem 'thin' 

----------------------------------------
2. Now ! run bundle install   command for install gem and it's dependency.

3. create a faye.ru file and add given line (a rackup file for run Faye server ).

require 'rubygems'
require 'thin'
require 'faye'

faye_server = Faye::RackAdapter.new(:mount => '/faye', :timeout => 45)
run faye_server


4. Now add line to your application.erb file

<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' => true %>


Now ! adding a method with name broadcast or any name which is subtable for you in websoket.rb (first create websoket.rb file inside initializers ) .

#======confi/initializers/websoket.rb


module Websocket
  def broadcast(channel, msg)
    message = {:channel => channel, :data => msg}
    uri = URI.parse("http://localhost:9292/faye")
    Net::HTTP.post_form(uri, :message => message.to_json)
  end
end



Note: If you want to use this method as a helper method then you add this inside application_helper.rb for view.(I include this method into model for sending notification as per my business logic ) for more detail watch RailsCast 260.

Inside this method channel is use for sending messages on a particular URL and MSG is used for send messages on that particular channel.

example :

#===============include Websocket
 
 
 
Inside Notification.rb model
def send_invitation_notification
   broadcast("/users/#{user.id}", {username: "#{user.full_name }", msg: "Hello you are invited for project--| #{project.name} | please check your mail"})
end


I include Web-socket for access broadcast method in model. Now on browser when we call this method using console then it will get notification but first you have to create a view for this notification and a subscriber inside the view using Faye.Cilent('http://localhost:9292/faye').


Example:


<div id="websocket" style="background-color: #999999;">
</div>
<script>
$(function () {
var faye = new Faye.Client('http://localhost:9292/faye');
        faye.subscribe('/users/<%= current_user.id %>', function (data) {
            $('#websocket').text(data.username + ": " + data.msg);
        });
    });
</script>

5. Now ! Run your faye.ru file using terminal


rackup faye.ru -s thin -E prodcution




6. Open User show page something like http://localhost:3000/users/1

7. Now ! send notification using terminal



u = Notification.first
u.broadcast("/projects/16", {username: "your name ",msg: "Hello you did it "})



For more detail about faye gem see it's official website - http://faye.jcoglan.com/ruby.html


Friday, 5 June 2015

Condition on Associations in rails

Unsaved objects and associations

You can manipulate objects and associations before they are saved to the database, but there is some special behavior you should be aware of, mostly involving the saving of associated objects.
You can set the :autosave option on a has_one, belongs_to, has_many, or has_and_belongs_to_many association. Setting it to true will always save the members, whereas setting it to false will never save the members. More details about :autosave option is available at AutosaveAssociation.

One-to-one associations

  • Assigning an object to a has_one association automatically saves that object and the object being replaced (if there is one), in order to update their foreign keys - except if the parent object is unsaved (new_record? == true).
  • If either of these saves fail (due to one of the objects being invalid), an ActiveRecord::RecordNotSaved exception is raised and the assignment is cancelled.
  • If you wish to assign an object to a has_one association without saving it, use the build_association method (documented below). The object being replaced will still be saved to update its foreign key.
  • Assigning an object to a belongs_to association does not save the object, since the foreign key field belongs on the parent. It does not save the parent either.

Collections

  • Adding an object to a collection (has_many or has_and_belongs_to_many) automatically saves that object, except if the parent object (the owner of the collection) is not yet stored in the database.
  • If saving any of the objects being added to a collection (via push or similar) fails, then push returns false.
  • If saving fails while replacing the collection (via association=), an ActiveRecord::RecordNotSaved exception is raised and the assignment is cancelled.
  • You can add an object to a collection without automatically saving it by using the collection.build method (documented below).
  • All unsaved (new_record? == true) members of the collection are automatically saved when the parent is saved.

 

Customizing the query

Associations are built from Relations, and you can use the Relation syntax to customize them. For example, to add a condition:


class Blog < ActiveRecord::Base
  has_many :published_posts, -> { where published: true }, class_name: 'Post'
end
 
 
Inside the -> { ... } block you can use all of the usual Relation methods.
 


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...