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?

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