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.








Friday, 24 April 2015

Running rails application locally and make it available on public url


 However in practice you need to serve your local web server publicly.Its pretty good and easy to do that with the help of gem 'proxylocal'.

ProxyLocal proxies your local web-server and makes it publicly available over the internet. This application is splitted into client and server. The server is running on proxylocal.com. The client is written in ruby and distributed as gem.
  
1.Installation: Write inside your gem file gem 'proxylocal' or  run

gem install proxylocal inside your application.

2.Running your server: Just run your web server after that run following command 

 `proxylocal 3000 --host you_host_name` // assuming your server is running on port 3000.

now your local web server is available at:
http://ramlaxman.staging.t.proxylocal.com/


if you ar enot giving any host name in the command then proxylocal gem will give you a random path like `http://*.t.proxylocal.com/`.


references: proxylocal-gem.

Friday, 20 March 2015

How to serve a perticular sub url from different server by Nginx HTTP Proxy Pass

One reason to proxy to other servers from Nginx is the ability to scale out your infrastructure. Nginx is built to handle many concurrent connections at the same time. This makes it ideal for being the point-of-contact for clients. The server can pass requests to any number of backend servers to handle the bulk of the work, which spreads the load across your infrastructure. This design also provides you with flexibility in easily adding backend servers or taking them down as needed for maintenance.

Another instance where an http proxy might be useful is when using an application servers that might not be built to handle requests directly from clients in production environments. Many frameworks include web servers, but most of them are not as robust as servers designed for high performance like Nginx. Putting Nginx in front of these servers can lead to a better experience for users and increased security.

Here is an example of proxy pass in nginx:

The most straight-forward type of proxy involves handing off a request to a single server that can communicate using http.

example:

location /some_url {
    proxy_pass http://example.com;
}


In the above configuration, no URI is given at the end of the server in the proxy_pass definition. For definitions that fit this pattern, the URI requested by the client will be passed to the upstream server as-is.
when a request for /some_url/hello_url is handled by this block, the request URI will be sent to the example.com server as http://example.com/some_url/hello_url.

Sometimes, this kind of replacement is impossible. In these cases, the URI at the end of the proxy_pass definition is ignored and either the original URI from the client or the URI as modified by other directives will be passed to the upstream server.

For instance, when the location is matched using regular expressions, Nginx cannot determine which part of the URI matched the expression, so it sends the original client request URI. Another example is when a rewrite directive is used within the same location, causing the client URI to be rewritten, but still handled in the same block. In this case, the rewritten URI will be passed.

Example of proxy pass with headers:

location /learn {
rewrite   /learn(.*)$  $1/  break;
proxy_pass http://45.55.156.88:80;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header Host $host;
}


when a request for /some_url ,the request URI will be sent to the example.com server as http://example.com/some_url.

Friday, 13 March 2015

Adding social share buttons in rails application by using 'shareable' gem

However in practice you need to add social sharing buttons inside your rails applications. Its very easy to add social buttons in rails application by using 'shareable' gem.

here is an example:

1. Install gem:

 put gem  'shareable' in your gem file.
then run bundle install.

2. Show buttons in rails view:
put <%= render_shareable %> in your view // this will add default buttons in your view.

3. Customizing buttons: you can customize buttons by using the helper methods.
 for more detail click on read more link. read more.

Friday, 20 February 2015

General settings for deployment in deploy.rb Capistrano

Here some general settings and use of them in capistrano deployment.

1. set_scm: Set protocol to copy code from your repository to server.
   set: 'git' // git protocol will used for deployment.

2. Set repository: set path of your git repository.
3. deploy_via : This is very important setting. There are two ways to set this variable
  3.1 Set to copy
         set :deploy_via, :copy
 this will copy all code with all meta data of repository like branch info n all.This will be a slow process because capistrano will perform a scp from your repository to server.

 3.2 Set to export: 
       set :deploy_via, :export

This is faster a bit because it will clone repository to the server it leave metadata of the repository.

4. Set branch: Set default branch to be deployed.There are many ways you can set it like:

 4.1 Set it manually: Just hard code the branch name.  
        set :branch ,'branch_name'
  4.2 Ask before deployment: Use Capistrano::CLI.ask to take branch name at deployment time.

set :branch do
default_branch = Capistrano::CLI.ask('Enter branch name')
end

4.3 Use current branch: You can use current working branch like:
  set :branch do
   default_branch = `git rev-parse --abbrev-ref HEAD`.chomp
  end

These are some common settings to keep in mind before writing a deployment script in capistrano.

Enjoy!!!!!

Friday, 13 February 2015

Working with SAML(Security Assertion Markup Language) in rails by 'ruby-saml' gem

Security Assertion Markup Language (SAML, pronounced sam-el) is an XML-based, open-standard data format for exchanging authentication and authorization data between parties, in particular, between an identity provider and a service provider. SAML is a product of the OASIS Security Services Technical Committee. SAML dates from 2001; the most recent major update of SAML was published in 2005, but protocol enhancements have steadily been added through additional, optional standards.

Here is an example of implementing saml-sso in rails applications by using 'ruby-saml':

1. Install gem:

     gem install 'ruby-saml' or whrite gem 'ruby-saml' in your app's gem file.

2. Create a controller named 'saml'.

3. Configure settings:

 3.a create a yml file inside app/config/saml_settings.yml.
 3.b add the following code inside the yml file

idp:
  sso_target_url: idp_provider's_saml_auth_path
  slo_target_url: idp_provider's_saml_logout_path

so:
  assertion_consumer_service_url: Service_providers_consume_path
  issuer: service_provider's_path
  assertion_consumer_logout_service_url: service_provider's_saml_logout_path

4.Load all saml settings in your saml_controller.

5.Send login request to idp:

 def init  request = OneLogin::RubySaml::Authrequest.new
  redirect_to(request.create(saml_settings))
end

6.Handle Idp response for login:

def consume  response = OneLogin::RubySaml::Response.new(params[:SAMLResponse])
  response.settings = saml_settings
  if response.is_valid? && user = User.find_or_create_by(email: response.name_id)
    session[:user_id] = user.id
    redirect_to root_url
  else    redirect_to login_path
  end
end

the above example is for implementing single sign on in a rails app.

Friday, 6 February 2015

Templating in Rails by using .docx and unoconv

In practice we often use to convert docx files in several forms as like PDF and doc file by using unoconv utility in Ubuntu.

There is a general issue with  converting docx files having image in that file i.e image background will be change.while converting docx file to doc unoconv change image property. if you set image background to no fill in docx then it will be 'white background' in doc file.


To resolve this issue you can do the following steps:
1. Extract .docx file and go to 'test_docx_files/word/media' folder.
2. Put your image inside  'test_docx_files/word/media' folder.
3. Convert your image to '.emf' file and rename to to 'image1.emf'.
4. Come to  'test_docx_files' and run following command:

`zip -r ../hest1.docx .`

this will create a .docx file named 'test1.docx' outside of the 'test_docx_files' folder.
5. convert this .docx file to .doc file.

Now you can see your image is having same property as like in .docx file.

Friday, 30 January 2015

Export Data to csv/xls in Rails by using to_xls-rails gem

How ever in practice we require to export data in several forms like 'csv' and 'xls'.Its very easy to export data in csv or xls format in rails application.

Here an example of exporting data:

1. write gem 'to_xls-rails' and run `bundle install`.
2. write following code in controller:

 respond_to do |format|
    format.html # don't forget if you pass html
    format.xls {
    filename = "Posts-#{Time.now.strftime("%Y%m%d%H%M%S")}.xls"
    send_data(@posts.to_xls, :type => "text/xls; charset=utf-8; header=present", :filename => filename)
     }
  end

3. In your view write following code:

<%= link_to 'Excel Download', posts_path(:format => :xls) %>

4. Specify mime type inside the mime_type.rb:

Mime::Type.register "application/xls", :xls



enjoy!!