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.
 


Friday, 29 May 2015

Creating Ruby Script as a Sevices in Ubuntu 15.04

Simple services

Here is the simplest possible service file that starts MyRubyScript with options that work for me on my computer. Save it as /etc/systemd/system/my_ruby_script.service :


[Unit]
Description=Virtual Distributed Ethernet

[Service]
ExecStart=/home/anil/.rvm/rubies/ruby-2.2.0/bin/ruby my_ruby_script.rb

[Install]
WantedBy=multi-user.target




Automatic restarts

Let's also add the proper dependency on the system logger and tell systemd to restart my_ruby_script_switch if it crashes due to an uncaught signal (although it never happened to me):

[Unit]
Description=My Ruby Script Demo
After=syslog.target


[Service]

WorkingDirectory=/home/anil/new_workers

ExecStart=/home/anil/.rvm/rubies/ruby-2.2.0/bin/ruby my_ruby_script.rb

Restart=on-abort

[Install]
WantedBy=multi-user.target



Systemd consists of two main concepts: a unit and a target. A unit is a configuration file that describes the properties of the process that you'd like to run. This is normally a docker run command or something similar. A target is a grouping mechanism that allows systemd to start up groups of processes at the same time. This happens at every boot as processes are started at different run levels.
systemd is the first process started on CoreOS and it reads different targets and starts the processes specified which allows the operating system to start. The target that you'll interact with is the multi-user.target which holds all of the general use unit files for our containers.
Each target is actually a collection of symlinks to our unit files. This is specified in the unit file by WantedBy=multi-user.target. Running systemctl enable foo.service creates symlinks to the unit inside multi-user.target.wants Click - for more detail

Friday, 22 May 2015

Speed up Active record With inclulde method.

When you’re building a new Rails app, ActiveRecord’s defaults will take you far. Querying with .where, inserting with .save — it’s all so easy, and it’s fast enough.
But after a while — when a page of mostly simple content takes a second or more to come back from the server, when you start seeing 504 Gateway Timeout errors coming back from nginx because it’s taking too long to process the CSV you uploaded — that’s when you know you’re going to have to spend some time on performance.
You could solve a lot of these problems with caching. But that adds a whole extra layer of complication. Between expiration, nesting partials, and bugs that only reproduce in production, it’s a headache you don’t need right now.
Instead, you can spend some time fixing the most common performance problem I’ve seen in Rails apps: hitting your database too much.
Even if you’re running the database on the same machine, there’s a lot of connection overhead that’ll slow you down. And if your database is on another machine, fetching data that often will just destroy you.
But you don’t have to go too far from the simplicity of Rails to see drastic improvements in your app’s response time.

You’re trying to find ten restaurants along with with their reviews, and you’re doing eleven SQL calls!

This is called the “N+1 query problem”: for every restaurant, you’re doing one query for the restaurant data, plus one query for each of their associated reviews. You can probably imagine how bad it becomes the deeper you go. Imagine if you also wanted to grab each restaurant’s address, as well as each address’ phone number.
You’ll run into this problem when you loop over a list of objects and try to query their associations:

app/views/restaurants/index.html.erb
<% @restaurants.each do |restaurant| %>
  <tr>
    <td><%= restaurant.name %></td>
    <td><%= restaurant.review_average %></td>
    ...
 
You don’t need to hit the database N+1 times. You want to hit it at most twice: once for the restaurants you’re trying to find, and once for all of the reviews associated with all of those restaurants.
This is called “eager loading,” and you can do it really easily with .includes:

app/controllers/restaurants_controller.rb

def index
  @restaurants = Restaurant.all.includes(:reviews)
end
 
Or, if you want to do something more complicated, like preload all the addresses and the reviews’ authors:

app/controllers/restaurants_controller.rb
def index
  @restaurants = Restaurant.all.includes([{:reviews => author}, :address])  
end

Or, if you want to do something more complicated, like preload all the addresses and the reviews’ authors:

app/controllers/restaurants_controller.rb
def index
  @restaurants = Restaurant.all.includes([{:reviews => author}, :address])
end
You have to specify the associations you want to preload, using that array and hash syntax. Rails will do the best it can at consolidating down those calls:

For more Click

 

 

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