Month: April 2015

Simple CRUD operations with file upload ruby on rails

The controller file

class WelcomeController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def index
  	
  end
  def list
  	@tweets = Tweet.all
  end
  def save

	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file
	File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

  	t = Tweet.new
	t.title = params[:title]
	t.tweet = params[:tweet]
	t.file = name
	t.save
        
        

        flash[:notice] = "Tweet saved!"
        redirect_to :action => 'list'
  end
  def new
  end
  def edit
       @tweet = Tweet.find(params[:id])
       
  end
  def delete
       t = Tweet.find(params[:id])
       t.destroy
       flash.keep[:notice] = "Tweet deleted!"
       redirect_to :action => 'list'
  end
 def update
	upload = params[:upload]
        name =  upload['datafile'].original_filename
	directory = "public/tweet_files"
	# create the file path
	path = File.join(directory, name)
        # write the file
	File.open(path, "wb") { |f| f.write(upload['datafile'].read) }

       t = Tweet.find(params[:id])
       t.title = params[:title]
       t.tweet = params[:tweet]
       t.file = name
       t.save
       flash.keep[:notice] = "Tweet updated!"
       redirect_to :action => 'list'
  end
end

view files list.html.erb

<style>
table{
border-collapse: collapse;
    font-family: "Trebuchet MS",Arial,Helvetica,sans-serif;
    width: 100%;
}
table, td, th {
    border: 1px solid green;
    text-align:center;
}

th {
    background-color: green;
    color: white;
    font-weight:bold;
}
</style>
<%= notice %><br>
<%= link_to "Add new",:controller => :welcome, :action => :new %>
<br>
<table>
<thead><tr><th>Title</th><th>Tweet</th><th>Image</th><th>Edit</th><th>Delete</th></tr></thead>
<tbody>
<% @tweets.each do |tweet| %>
<tr>
 <td><%=  tweet.title %></td>
 <td><%=  tweet.tweet %></td>
<td><%=  image_tag("/tweet_files/#{tweet.file}") %></td>
<td><%= link_to "Edit",:controller => :welcome, :action => :edit ,:id => tweet.id %> </td>
<td><%= link_to "Delete",:controller => :welcome, :action => :delete,:id => tweet.id  %> </td>
</tr>
<% end %>
</tbody>
<% if @tweets.size == 0 %>
<em>No tweets found</em>
<% end %>


edit.html.erb


<%= form_tag({controller: "welcome", action: "update"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Update Tweet") %>
 <br>
 
  <%= text_field_tag "title" , @tweet.title %> 
<br>
 
  <%= text_field_tag "tweet" , @tweet.tweet %>
<br>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
<%=  image_tag("/tweet_files/#{@tweet.file}") %>
  <%= submit_tag("update") %>
<% end %>


new.html.erb


<%= form_tag({controller: "welcome", action: "save"}, method: "post",multipart: true) do %>
  <%= label_tag(:tweet, "Add Tweet") %>
<br>
  <%= text_field_tag "title" %>
<br>
  <%= text_field_tag "tweet" %>
<br>
<p><label for="upload_file">Select File</label> : 
<%= file_field 'upload', 'datafile' %></p>
  <%= submit_tag("Save") %>
<% end %>



routes.rb

   root 'welcome#list'
   post 'welcome/save' => 'welcome#save'
   get  'welcome/new'  => 'welcome#new'
   get  'welcome/edit/:id'  => 'welcome#edit'
   get  'welcome/delete/:id'  => 'welcome#delete'
   post  'welcome/update/:id'  => 'welcome#update'

Here is how to add migrations to active records…adding column file here

$ rails generate migration add_file_to_tweets file:string
$ rake db:migrate

Here is how to create folder

cd myrailsproject
cd public
mkdir tweet_files
Advertisements

Setting up an application with mysql database on rails server on ubuntu 14.04

Simple steps to be followed
I assume you have installed rails, ruby gems and mysql

1) Create a new application with mysql database.

— name of application : myapplication
— db driver mysql

	$ rails new myapplication -d mysql
        

2) Run your application on rails server

CD to myapplication

	$ rails server
       

3) Create a database for the application
CD to myapplication

	$ rails db
        

Enter the password for root user

	mysql> create database mydb;
	mysql> create user abc identified by 'PASSWORD';
	mysql> grant all privileges on mydb.* to abc@localhost identified by 'PASSWORD';
	mysql>quit
	

4) Now place the username,password and database name in database.yml file under config folder of your app.
5) Goto routes.rb
— uncomment root ‘welcome#index’

6) Create a controller class welcome_controller.rb under controller folder and add an action index to it.

	class WelcomeController < ApplicationController
		def index
		end
	end
        

7) Create a view file for function index under views/welcome/index.html.erb
write

<h1>Hello Rails</h1>

to view file.
8) Now run the rails server as
CD to myapplication

   $ rails server
  

open in browser —> localhost:3000

You will see Hello Rails in browser window.

Upload image plus all form data using jquery

Html

<form action="" method="post" enctype="multipart/form-data" id="form_portfolio_save">
				<input type="text" name="title" id="title" placeholder=""/><br/>
				<textarea id="about_project" name="about_project">About project</textarea><br/>
				<input type="file" name="photo" id="port_image" placeholder="Add Files"/><br/>
				<input type="text" name="caption" id="caption" placeholder="Image caption"/><br/>
				<input type="button" id="submit" value="Submit" class="button submit" onclick="save_portfolio();return false;"/>
				<input type="button" class="button cancel" id="submit" value="Cancel" />
			  </form>

JQuery

function save_portfolio(){
		var fd = new FormData();
		var file_data = $('input[name^="photo"]')[0].files; 
		for(var i = 0;i<file_data.length;i++){
			fd.append("file_"+i, file_data[i]);
		}
		var  other_data = $("#form_portfolio_save").serializeArray();
		 $.each(other_data,function(key,input){
			fd.append(input.name,input.value);
		});
	   
		$.ajax({
		url : 'save_portfolio.php',
		type : "post",
		data : fd,
		cache: false,
		contentType: false,
		processData: false,
		success : function(data){
				$("#append_portfolio").append(data);
				
		}
	});
	}

PHP

include("includes/session.php");
include("includes/database.php");
if(!empty($_FILES['file_0'])){
		$filename = time().$_FILES['file_0']['name'];
		$path= "upload/user_portfolio/".$filename;
		move_uploaded_file($_FILES['file_0']['tmp_name'],$path);
	}
$query = "insert into user_portfolio(title,description,images,image_captions,employee_id) values('".$_POST['title']."','".$_POST['about_project']."','".$filename."','".$_POST['caption']."','".$_SESSION['user_details']['id']."')";
mysql_query($query);

PAYPAL PAYMENT DATA TRANSFERS (PDT)

To use PDT, you must activate PDT and Auto Return in your PayPal account profile. You must also acquire a PDT identity token, which is used in all PDT communication you send to PayPal.

Follow these steps to configure your account for PDT:

1)Log in to your PayPal account.
2)Click the Profile subtab.
3)Click the My Selling Tools button in the left column.
4)Find the Selling online section and click Update in the Website preferences row.
5)Under Auto Return for Website Payments, click the On radio button.
6)For the Return URL, enter the URL on your site that will receive the transaction ID posted by PayPal after a customer payment.
7)Under Payment Data Transfer, click the On radio button.
8)Click Save.
9)Find the Selling online section and click Update in the Website preferences row again.
10)Scroll down to the Payment Data Transfer section of the page and take note of your PDT identity token.

Create the form now with notify url and cancel url

<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post" accept-charset="utf-8"> 
    <p> 
    <input type="hidden" name="cmd" value="_xclick" /> 
    <input type="hidden" name="charset" value="utf-8" /> 
    <input type="hidden" name="business" value="paypal@business.example.com" /> 
    <input type="hidden" name="item_name" value="Stuffed bear" />
    <input type="hidden" name="item_number" value="BEAR05" />
    <input type="hidden" name="amount" value="20.00" />
    <input type="hidden" name="currency_code" value="USD" />
    <input type="hidden" name="return" value="http://business.example.com/order/123/" /> 
    <input type="hidden" name="cancel_return" value="http://business.example.com/order/123/" />
    <input type="hidden" name="bn" value="Business_BuyNow_WPS_SE" /> 
    <input type="image" src="https://www.paypal.com/en_US/i/btn/btn_buynowCC_LG.gif" name="submit" alt="Buy Now" />
    </p> 
</form>

Catch the return now as $_GET[‘tx’] and repost to paypal

if(isset($_GET['tx']))
{
  $tx = $_GET['tx'];
  $request = curl_init();
  curl_setopt_array($request, array
(
  CURLOPT_URL => 'https://www.sandbox.paypal.com/cgi-bin/webscr',
  CURLOPT_POST => TRUE,
  CURLOPT_POSTFIELDS => http_build_query(array
    (
      'cmd' => '_notify-synch',
      'tx' => $tx,
      'at' => $your_pdt_identity_token,
    )),
  CURLOPT_RETURNTRANSFER => TRUE,
  CURLOPT_HEADER => FALSE,
  // CURLOPT_SSL_VERIFYPEER => TRUE,
  // CURLOPT_CAINFO => 'cacert.pem',
));

// Execute request and get response and status code
$response = curl_exec($request);
$status   = curl_getinfo($request, CURLINFO_HTTP_CODE);
if($status == 200 AND strpos($response, 'SUCCESS') === 0)
{
    // Further processing
}
else
{
    // Log the error, ignore it, whatever 
}
// Close connection
curl_close($request);
}

Add custom marker to Google map

<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>	<!-- Google Maps API -->
	<script>
	var map;	// Google map object
	
	// Initialize and display a google map
	function Init()
	{
		// Create a Google coordinate object for where to center the map
		var latlngDC = new google.maps.LatLng( 38.8951, -77.0367 );	// Coordinates of Washington, DC (area centroid)
		
		// Map options for how to display the Google map
		var mapOptions = { zoom: 12, center: latlngDC  };
		
		// Show the Google map in the div with the attribute id 'map-canvas'.
		map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
		
		// Place a standard Google Marker at the same location as the map center (Washington, DC)
		// When you hover over the marker, it will display the title
		var marker = new google.maps.Marker( { 
			position: latlngDC,     
			map: map,      
			title: 'Washington, DC',
			icon : 'bigcity.png',					// image to display as the marker
			animation: google.maps.Animation.BOUNCE	// set marker to bounce
		});
	}
	
	// Call the method 'Init()' to display the google map when the web page is displayed ( load event )
	google.maps.event.addDomListener( window, 'load', Init );

	</script>
	<style>
	/* style settings for Google map */
	#map-canvas
	{
		width : 500px; 	/* map width */
		height: 500px;	/* map height */
	}
	</style>
</head>
<body>
	<!-- Dislay Google map here -->
	<div id='map-canvas' ></div>
</body>

Time Ago function


function time_ago($date)

		{

				if(empty($date)) {

							return "No date provided";

				}

				$periods = array("second", "minute", "hour", "day", "week", "month", "year", "decade");

				$lengths = array("60","60","24","7","4.35","12","10");

				$now = time();

				$unix_date = strtotime($date);

				// check validity of date

				if(empty($unix_date)) {

						return "Bad date";

				}

				// is it future date or past date

				if($now > $unix_date) {

						$difference = $now - $unix_date;

						$tense = "ago";

				} else {

						$difference = $unix_date - $now;
						$tense = "from now";}

						for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {

						$difference /= $lengths[$j];

				}

				$difference = round($difference);

				if($difference != 1) {

						$periods[$j].= "s";

				}

						return "$difference $periods[$j] {$tense}";

               }

Pass variable to TCPDF class header or any class function


class MYPDF extends TCPDF {
	public $template;
	
	public function setData($template){
    $this->template = $template;
	}
	public function Header() {
        // get the current page break margin
        $bMargin = $this->getBreakMargin();
        // get current auto-page-break mode
        $auto_page_break = $this->AutoPageBreak;
        // disable auto-page-break
        $this->SetAutoPageBreak(false, 0);
        // set bacground image
        $img_file = "uploads/template_background_image/".$this->template.".png";
        $this->Image($img_file,0, 100, 390, 397, '', '', '', false, 300, '', false, false, 0);
        // restore auto-page-break status
        $this->SetAutoPageBreak($auto_page_break, $bMargin);
        // set the starting point for the page content
       
       
    }
	}


$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, array(400,500), true, 'UTF-8', false);
$pdf->setData($template);