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

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