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 




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

 

 

Friday 15 May 2015

PostgreSQL in Rails With Active Record

PostgreSql is used as a database in various application and also in rails application. Here some useful data type and it's behavior which are use in rails with PostgreSql.

 JSON Type

         Here we adding a column with json data type and then store the data as json formate on Create

# db/migrate/20131220144913_create_events.rb

create_table :events do |t|
t.json 'payload'
end

# app/models/event.rb

class Event < ActiveRecord::Base
end

# Usage

Event.create(payload: { kind: "user_renamed", change: ["jack", "john"]})
event = Event.first
event.payload # => {"kind"=>"user_renamed", "change"=>["jack", "john"]}
## Query based on JSON document

# The -> operator returns the original JSON type (which might be an object), whereas ->> returns text

Event.where("payload->>'kind' = ?", "user_renamed") 



For more Information:  Json Type Def


Network Address Types

The types inet and cidr are mapped to Ruby IPAddr objects. The macaddr type is mapped to normal text

# db/migrate/20140508144913_create_devices.rb

create_table(:devices, force: true) do |t|
t.inet 'ip'
t.cidr 'network'
t.macaddr 'address'
end

# app/models/device.rb
class Device < ActiveRecord::Base
end
# Usage
macbook = Device.create(ip: "192.168.1.12",network: "192.168.2.0/24",address: "32:01:16:6d:05:ef")
macbook.ip
# => #

macbook.network
# => #

macbook.address
# => "32:01:16:6d:05:ef"



Bit String Types

Bit strings are strings of 1's and 0's. They can be used to store or visualize bit masks. There are two SQL bit types: bit(n) and bit varying(n), where n is a positive integer.
(Mask means to block.Masking is the process by which ,only required data is retained and the rest is masked (blocked))
bit type data must match the length n exactly; it is an error to attempt to store shorter or longer bit strings. bit varying data is of variable length up to the maximum length n; longer strings will be rejected. Writing bit without a length is equivalent to bit(1), while bit varying without a length specification means unlimited length.

# db/migrate/20131220144913_create_users.rb
create_table :users, force: true do |t|
t.column :settings, "bit(8)"
end

# app/models/device.rb
class User < ActiveRecord::Base end # Usage User.create settings: "01010011" user = User.first user.settings # => "01010011"
user.settings = "0xAF"
user.settings # => 10101111
user.save!



For more information: Click

Range Types

Range types are data types representing a range of values of some element type (called the range's subtype). For instance, ranges of timestamp might be used to represent the ranges of time that a meeting room is reserved. In this case the data type is tsrange (short for "timestamp range"), and timestamp is the subtype. The subtype must have a total order so that it is well-defined whether element values are within, before, or after a range of values.
Range types are useful because they represent many element values in a single range value, and because concepts such as overlapping ranges can be expressed clearly. The use of time and date ranges for scheduling purposes is the clearest example; but price ranges, measurement ranges from an instrument, and so forth can also be useful.

This type is mapped to Ruby Range objects.


# db/migrate/20130923065404_create_events.rb
create_table :events do |t|
t.daterange 'duration'
end

# app/models/event.rb
class Event < ActiveRecord::Base end # Usage Event.create(duration: Date.new(2014, 2, 11)..Date.new(2014, 2, 12)) event = Event.first event.duration # => Tue, 11 Feb 2014...Thu, 13 Feb 2014

## All Events on a given date
Event.where("duration @> ?::date", Date.new(2014, 2, 12))

## Working with range bounds
event = Event.
select("lower(duration) AS starts_at").
select("upper(duration) AS ends_at").first

event.starts_at # => Tue, 11 Feb 2014
event.ends_at # => Thu, 13 Feb 2014



Bytea (Binary Type)

A binary string is a sequence of octets (or bytes). Binary strings are distinguished from character strings in two ways. First, binary strings specifically allow storing octets of value zero and other "non-printable" octets (usually, octets outside the range 32 to 126). Character strings disallow zero octets, and also disallow any other octet values and sequences of octet values that are invalid according to the database's selected character set encoding. Second, operations on binary strings process the actual bytes, whereas the processing of character strings depends on locale settings. In short, binary strings are appropriate for storing data that the programmer thinks of as "raw bytes", whereas character strings are appropriate for storing text.
The bytea type supports two external formats for input and output: PostgreSQL's historical "escape" format, and "hex" format. Both of these are always accepted on input. The output format depends on the configuration parameter bytea_output; the default is hex. (Note that the hex format was introduced in PostgreSQL 9.0; earlier versions and some tools don't understand it.)
The SQL standard defines a different binary string type, called BLOB or BINARY LARGE OBJECT. The input format is different from bytea, but the provided functions and operators are mostly the same.


# db/migrate/20140207133952_create_documents.rb
create_table :documents do |t|
t.binary 'payload'
end

# app/models/document.rb
class Document < ActiveRecord::Base
end
# Usage
data = File.read(Rails.root + "tmp/output.pdf")
Document.create payload: data



Friday 8 May 2015

Active Record Migration Rails

Migrations can manage the evolution of a schema used by several physical databases. It's a solution to the common problem of adding a field to make a new feature work in your local database, but being unsure of how to push that change to other developers and to the production server. With migrations, you can describe the transformations in self-contained classes that can be checked into version control systems and executed against another database that might be one, two, or five versions behind.

Running migration:

where MyNewMigration is the name of your migration. The generator will create an empty migration file timestamp_my_new_migration.rb in the db/migrate/ directory where timestamp is the UTC formatted date and time that the migration was generated.
There is a special syntactic shortcut to generate migrations that add fields to a table.

 rails generate migration add_fieldname_to_tablename fieldname:string

class AddFieldnameToTablename < ActiveRecord::Migration
def change
add_column :tablenames, :field, :string
end
end 


To run migrations against the currently configured database, use rake db:migrate. This will update the database by running all of the pending migrations, creating the schema_migrations table (see “About the schema_migrations table” section below) if missing. It will also invoke the db:schema:dump task, which will update your db/schema.rb file to match the structure of your database.
To roll the database back to a previous migration version, use rake db:migrate VERSION=X where X is the version to which you wish to downgrade. Alternatively, you can also use the STEP option if you wish to rollback last few migrations. rake db:migrate STEP=2 will rollback the latest two migrations.

For more detail  : Active Record Migration

Friday 1 May 2015

how to install Rmagick gem in Ruby on Rails applications

After upgrading my Ubuntu 14.10 to 15.04 my Rmagick gem is not working in any application with a specific version then first i remove the version of rmagick gem inside the Gemfile of rails application and then i install first imagemagick .


1.sudo apt-get install imagemagick


After install imagemagick install package of imagemagick for install Rmagick gem by this command.

2. sudo apt-get install libmagickwand-dev



Now ! first exit the rails directory then again goto rails directory and run the bundle command. ;)

It's working for me ! ...

Friday 24 April 2015

Link-List Navigation for Shopify (Nested Navigation).

Main Menu is header menu list on Front of Page and for adding a category drop down menu. Click on Adding Link list and give the name and add link in this panel. 
 
Note: The Category name(Sub navigation name) is also add in Main Menu as a collection.
 
Adding Link List

 *Name = Category 

 *Add Link = Commercial, Residential

Main Menu

Edit Link list

Friday 17 April 2015

Cross-Domain Communication by iFrame Usinig javascript (onHashchangeEvent)

In iframe if we are on same domain then it's not to difficult to sending data between application and iFrame but what we do when both are different domain so there is something trick or a concept to sending data between different domain.

i Using javascript onhashchange event and first some code that will encode arbitrary data (as long as it’s JSON encodable) and put it into the hash value of the desired iframe.

function sendIFrameData( frame, data ){
    var idx = frame.src.indexOf('#'), url = frame.src;
    if ( idx > -1 ){
        url = url.substr(0, idx);
    }
   
    frame.src = url + '#' + window.btoa(JSON.stringify(data));
}

Now on the iframe side, let’s write a function to decode the data.

function getHashData(){
    var data;
    try {
        data = JSON.parse(window.atob(window.location.hash.substr(1)));
    } catch( e ){}
    return data;
}



In my application i add this code this is working for me ... !
iframe on my domain, and send it some messages.

// send arbitrary data to the iframe


sendIFrameData( frame, { text: "Hello world" } );
setTimeout(function(){
    sendIFrameData( frame, { text: "How are you today?" } );
}, 2000);





The iframe will listen to the hashchange event and log out what it hears.


var el = document.getElementById('log');
function showMsg(){
    var data = getHashData();
    if ( data && data.text ){
        el.innerHTML += "<br/>Received msg: " + data.text;
    }
}

// in case we sent data on first load.
showMsg();
// when the hash changes we check the new data and print it out
window.addEventListener('hashchange', function(){
    showMsg();
});

Load denied by X-Frame-Obtions in Rails


When i simply adding a iframe by java script  console then it's throw exception message  Load denied by X-Frame-Options: http://localhost:3000/home does not permit cross-origin framing 

Then after searching i found to solution by removing header "X-Frame-Obtions" on response in my Rails application i simply add a method.



after_filter :allow_iframe

private def allow_iframe

  response.headers.delete "X-Frame-Options"

end

And it's working for me...

Friday 10 April 2015

Active Model Dirty

Provides a way to track changes in your object in the same way as Active Record does.

The requirements for implementing ActiveModel::Dirty are:
include ActiveModel::Dirty in your object.
Call define_attribute_methods passing each method you want to track.
Call attr_name_will_change! before each change to the tracked attribute.
Call changes_applied after the changes are persisted. 
Call clear_changes_information when you want to reset the changes information.
Call restore_attributes when you want to restore previous data.

A newly instantiated Person object is unchanged:

person = Person.new
person.changed? # => false
Change the name:
person.name = 'Bob'
person.changed?       # => true
person.name_changed?  # => true
person.name_changed?(from: "Uncle Bob", to: "Bob") # => true
person.name_was       # => "Uncle Bob"
person.name_change    # => ["Uncle Bob", "Bob"]
person.name = 'Bill'
person.name_change    # => ["Uncle Bob", "Bill"]
Save the changes:
person.save
person.changed?      # => false
person.name_changed? # => false
Reset the changes:
person.previous_changes # => {"name" => ["Uncle Bob", "Bill"]}
person.reload!
person.previous_changes # => {}
Rollback the changes:
person.name = "Uncle Bob"
person.rollback!
person.name          # => "Bill"
person.name_changed? # => false
Assigning the same value leaves the attribute unchanged:
person.name = 'Bill'
person.name_changed? # => false
person.name_change   # => nil
Which attributes have changed?

Friday 27 March 2015

Geting S3 bucket data from aws after updating version v2 in ruby

After updating gem Version 1.50 to 2.0 of aws then i facing problem to download the data from S3 Bucket on aws server (Amazon web Services).
Aws::Errors::MissingRegionError: missing region; use :region option or export region name to ENV['AWS_REGION']

AWS.config(access_key_id: '...', secret_access_key: '...', region: 'us-west-2')
On last version of aws we smply use s3= AWS::S3.new       and fetching the bucket by using s3.buckets['bucketName']  

After Updating gem we first change the old Configuration and minor syntactical changes.
like Version 2 uses the Aws namespace, not AWS.

And configuration of region is like this.
  • Aws.config[:region] = 'Region'
  • Aws.config[:credentials] = Aws::Credentials.new(creds['AccessKeyId'], creds['SecretAccessKey'])

For S3 bucket fetching from aws server we use this..
s3 = Aws::S3::Client.new(credentials: credentials)
s3.get_object(bucket: 'Name', Key: 'objectKey')
resp = s3.list_objects(bucket: 'aws-sdk-core', max_keys: 2)
resp.contents.each do |object|
  puts "#{object.key} => #{object.etag}"
end
This method is use to get key by bucket Name.
get_object method simply return the method of s3 bucket in Paging Responses.



For more important method please goto Amazon (aws Documentation).













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