Friday, 8 May 2015

Using gem dropbox-sdk-ruby in Rails Application

Dropbox-sdk-ruby is a ruby library for the Dropbox core API.


1.Install Gem: you can run `gem install dropbox-sdk` from the terminal or  write following line in your gem file.

gem 'dropbox-sdk'

2. Using Gem: Create a file inside the config/initializers/ of your rails application.

There are following steps to use dropbox-sdk.

2.1 Require  gem inside your file:

 require 'dropbox_sdk'

2.2 Create an client_object of dropbox to use dropbox-api:

     @client = DropboxClient.new(YOUR_APP_SECRET_TOKEN)

2.3  Writing files to dropbox:

     @client.put_file(path_to_write, file, overwrite=true)

2.4 Read files to dropbox:

     @client.get_file(path, rev = revision)

Note: This is is onluy overview of this gem for more detail please click here.

Friday, 1 May 2015

Working with ruby Hash

A Hash is a dictionary-like collection of unique keys and their values. Also called associative arrays, they are similar to Arrays, but where an Array uses integers as its index, a Hash allows you to use any object type.

Hashes enumerate their values in the order that the corresponding keys were inserted.

Creating Hash: There are several ways to create a Hash. They are:

1.Implicit way: You can create a hash implicitly like:

_hash = { 'key1' =>  'value1' , 'key2' => 'value2' }

Hashes allow an alternate syntax form when your keys are always symbols. Instead of

_hash = { :key1 =>  'value1' , :key2 => 'value2' } 

You could write it as:

_hash = { key1:  'value1' , key2: 'value2' } 

2. Use ::new method to create Hash: You can also create hash  by ::new method.

_hash  = Hash.new

Default value of a Hash :  Hashes have a default value that is returned when accessing keys that do not exist in the hash. If no default is set nil is used. You can set the default value by sending it as an argument to ::new

 _hash  = Hash.new(10)

If you access a key which is not exist in the hash then default value will be return.In the above example

_hash[:key1]   // this will return 10 because key1 is not exists in hash, hence it will give result 10.

you can also set the default value as an array or another hash. Like:


_hash  = Hash.new([]) // setting default value as a blank array.

_hash[:a]    // will return a blank array.

_hash[:a]  << 20  // this will insert a value in default value that is an array.if you just print _hash then it is a blank hash no key in this hash but its default value has been changes from a blank array to a array that contains a value 20.


now if you print _hash[:b]  // will give result [20] because default value is changed.