Wednesday, 11 June 2014

ruby web development with simple sinatra app


recently got  into ruby coding for a project at my day time job. my first impression while i was learning ruby to get started was.. its so simple and beautiful,  yukihiro was certain right when he said programmer will enjoy coding in ruby, i certainly do enjoy coding in ruby. before getting into ruby, i coded in php and python, they certainly are pretty good languages but ruby is just different or in simple term "awesome".

thou the project i was working on does not have any web framework, project was more of coding standalone ruby scripts which does couple of web service call and render the html, it was fun period to learn and code.

i wanted to extend my skill to learn web framework and build same cool app with ruby. while googling about the ruby web framework.. obvious and the most worldly popular framework is the Rails. i want to learn rails but i wanted to start off with simple framework or micro framework, to get more handle on ruby coding.

google listed sinatra (micro framework), it is simple, easy and in real term small or micro framework as said over the web. in technical term  sinatra is more of DSL (domain specific language).  sinatra has really good documentation and is one of the best gem to start looking at while getting into the web development with ruby.

sinatra learning process was really amazing thanks to awesome ruby developer all over the world for building app and blogging about them. i have build medium and small application with sinatra, sinatra is always my first preference when ever i  want to build out pet project or web services for mobile application.

getting started with sinatra can be as simple as  requiring the gem  in a rb file


1
2
3
4
5
6
7
require 'sinatra'  #install gem from terminal first

get '/' do   # method to handle the request 

"hello world"   #response to request 

end 

note: do keep in mind to install sinatra gem with "gem install sinatra"
if you execute the script it will fire up  the WEbrick web server servering the web pages at default port 4567.

since sinatra is DSL designed to work over web and HTTP, its method are named closely to relate http verbs like "GET", "POST", "PUT" , "DELETE".

here is my code for complete crud operation in sinatra, a simple disc listing system, to manage a huge collection of dvds i have from earlier days. created as simple model with couple of fields and how i  arrange by the dvd disc in cases etc. UI is not fancy or smart, its pretty simple with angularjs, to have dynamic searching.

Github Link: https://github.com/zeet2020/simple-sinatra-app

do leave any comments or suggestion

Happy coding...



  

Monday, 10 September 2012

building simple applications with EasyGui library



i have been working on the python GUI library from few days now and found this amazing library to build simple gui application in matter of mins.

EasyGui uses the Tkinter to create the various gui components, its not as complex as PyQt or pygtk but fair enough to create a applications

here is example of simple file viewer which can be used to open a text files or code file for preview

#demo applicatio to create gui application using the easygui python library 

#importing the library file 
from easygui import *
import os
import sys

#simple application to browse and view files

#declaring the class fileviewer
class fileviewer:

    def __init__(self):
        #file open prompt
        self.menu()
        
    def menu(self):
        ch=indexbox('Simple File Viewer','Menu',['View File','Exit'])
        if ch ==0:
            #open file select and opne the file
            self.open_file()
            self.menu()
        elif ch ==1:
            #exit the applicaiton
            sys.exit()
            

    def open_file(self):
        #open the file in codebox
        file_name=fileopenbox("please select file to be opened")
        filename = os.path.normpath(file_name)
        text = open(filename,'rb').read()
        codebox("Contents of file " + filename, text=text)
        
        
if __name__ == '__main__':
    fileviewer()





Friday, 29 June 2012

simple cakephp CRUD operation

had some time to work on very popular framework cakephp, never find time and patience lookup the code generator console in cake. just jumped into coding and like to keep this handy... for creating a quick CRUD template 

 
<?php
simple crud operation in cakephp 2.x

create a controller which extend the base framework controller class
class TestsController extend AppController {
//read about class name convention in detail for the cakephp 

public $name = 'tests';
public $helper=array('Html','Form'); //for creating the form and html link in the view 
public function add(){
 if ($this->request->is('post')) {  //check whether request type is post before accepting the data 
            if ($this->Page->save($this->request->data)) {// save the data
                $this->Session->setFlash('Your data has been saved.'); // generate a flash message 
                $this->redirect(array('action' => 'index'));
            } else {
                $this->Session->setFlash('Unable to add your data.');
            }
        }
}


public function index(){
$this->set('test', $this->Test->find('all')); 
/* model which look up in the databases table "tests" and fetch all the content */ 
}

public function edit($id = null){
          $this->Test->id = $id;   // set the id to the model id value
                 if ($this->request->is('get')) { // check request type
               $this->request->data = $this->Test->read(); //read record with id and display the form regularly 
                 } else {
                      if ($this->Test->save($this->request->data)) {  // if post request save the data
                          $this->Session->setFlash('Your data has been updated.');
                          $this->redirect(array('action' => 'index'));
                     } else {
                          $this->Session->setFlash('Unable to update your data.');
                 }
}

   public function view($id=null){
        $this->Test->id = $id; //action to display the content or view the content
        $this->set('test', $this->Test->read());
   }

 public function delete($id=null){ // critical action 

   if ($this->request->is('get')) {
        throw new MethodNotAllowedException(); // throw error if request is get and break
        }
  
            if ($this->Test->delete($id)) { // deleted 
                 $this->Session->setFlash('The page with id: ' . $id . ' has been deleted.');
                  $this->redirect(array('action' => 'index'));
           
               }

}



}
?>






Thursday, 12 April 2012

zend CRUD action example

hi


starting off with create action / add action
 class ExampleController extends Zend_Controller_Action{  
 public function createAction(){  
    $form = // create a form or call a model form class  
    if ($this->getRequest()->isPost()) { // processing the form after the submission  
        if ($form->isValid($this->_request->getPost())) // check wheather the form data is valid  
    {  
 // do stuff  
         }  
                    }  
 }  
 $this->view->form=$form; // send the form to the view  
 }  
 //update action and modified action  
 class ExampleController extends Zend_Controller_Action{  
 public function updateAction(){  
     $id = $this->getRequest()->getParam('id');  
    $form = // create a form or call a model form class  
   if ($id > 0) {  
 if ($this->getRequest()->isPost()){  
      if ($form->isValid($this->_request->getPost())){  
            //if valid do some stuff  
 }else{  
   //reload the form with error message  
 }  
 }else{  
      //if the form not submitted load the form with default values  
 }  
 }  
 $this->view->form=$form; // send the form to the view  
 }  
 }  
 // view action  
 class ExampleController extends Zend_Controller_Action{  
 public function viewAction(){  
  $id = $this->getRequest()->getParam('id');  
 if($id>0){  
 // display content in the view template file  
 }  
 }  
 }  
 // delete acion  
 class ExampleController extends Zend_Controller_Action{  
 public function deleteAction(){  
    $id = $this->getRequest()->getParam('id');  
    if ($sid > 0) {  
    //do some stuff  
    $this->db->delete("id = $id");  
    $this->_redirect('');//redirection  
    }  
   }  
 }  

Sunday, 18 March 2012

palindrome in ruby

working with ruby code

simple method to check whether given string is palindrome. method will return true if the given string is palindrome or return false
 def palindrome?(string)  
   str=string.downcase;  
   str=str.gsub(/[^a-z]/,'');  
   return str.eql? str.reverse;  
 end  

Wednesday, 15 February 2012

yii framework popup example


in this example i will implement a simple popup form to create action from controller.i am using the gii for generating the code for the CRUD

code inside controller
 public function actionCreate()  
     {  
         $model=new ExampleModel;  
         // Uncomment the following line if AJAX validation is needed  
         //$this->performAjaxValidation($model);  
          if(isset($_POST['Apply']))  
          {  
             $model->attributes=$_POST['Apply'];  
          if($model->save()){ //save the record to the database  
        if (Yii::app()->request->isAjaxRequest) // check for ajax request  
          {  
         echo CJSON::encode(array(  // display message  
                   'status'=>'success',  
                   'div'=>"Classroom successfully added"  
               ));  
              exit;         
      }  
      else{  
    $this->redirect(array('post/view','id'=>$model->aid)); // if the condition fail redirect the user to post/view  
                       }  
                   }  
         }  
   if (Yii::app()->request->isAjaxRequest) // check the condition  
   {  
    echo CJSON::encode(array(  
    'status'=>'failure',  
    'div'=>$this->renderPartial('_form', array('model'=>$model), true)));  
      exit;         
   }  
   else{  
      $this->render('create',array(  // return the form  
      'model'=>$model,  
    ));  
                 }  
  $this->refreash();  
     }  
 below section is the code need to insert inside your view file where ever you want the popup to be displayed  
 code inside your view  
 <?php  
  echo CHtml::link('apply for job', "", // the link for open the dialog  
   array(  
     'style'=>'cursor: pointer; text-decoration: underline;',  
     'onclick'=>"{addClassroom(); $('#dialogClassroom').dialog('open');}"));  
 ?>  
 <?php  
 $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog  
   'id'=>'dialogClassroom',  
   'options'=>array(  
     'title'=>'Create classroom',  
     'autoOpen'=>false,  
     'modal'=>true,  
     'width'=>550,  
     'height'=>470,  
   ),  
 ));?>  
 <?php  
 $this->beginWidget('zii.widgets.jui.CJuiDialog', array( // the dialog  
   'id'=>'dialogClassroom',  
   'options'=>array(  
     'title'=>'Create classroom',  
     'autoOpen'=>false,  
     'modal'=>true,  
     'width'=>550,  
     'height'=>470,  
   ),  
 ));?>  
 <div class="divForForm"></div>  
 <?php $this->endWidget();?>  
 <script type="text/javascript">  
 // here is the magic  
 function addClassroom()  
 {  
   <?php echo CHtml::ajax(array(   // code for the javascript  
       'url'=>array('apply/create&id='.$model->id),  
       'data'=> "js:$(this).serialize()",  
       'type'=>'post',  
       'dataType'=>'json',  
       'success'=>"function(data)  
       {  
         if (data.status == 'failure')  
         {  
           $('#dialogClassroom div.divForForm').html(data.div);  
              // Here is the trick: on submit-> once again this function!  
           $('#dialogClassroom div.divForForm form').submit(addClassroom);  
         }  
         else  
         {  
           $('#dialogClassroom div.divForForm').html(data.div);  
           setTimeout(\"$('#dialogClassroom').dialog('close') \",300);  
         }  
       } ",  
       ))?>;  
   return false;  
 }  
 </script>  

Friday, 13 January 2012

the first time login in drupal

hi

it certainly look pretty simple to detect the first time login event using hook_user to check for "login" operation and check the users object "$user->login" value.

code:


 <?  
  function mycustom_user($op,&$edit,&$account,$category = NULL){  
 if($op == 'login'){  
 if($account->login == 0){ // check the last login  
 //do stuff here  
 }  
 }  
 }  
 ?>  



this work just fine if you want to impletement a redirection once the user login for the first time.

but what if you have to check users first time login on search page or user profile page.in that particular condition the above code does not work. because the
the value of user->login will be updated as soon as user login.

there is a simple module which manage the user Statistics called user_stats 
it manage the user login count which comes in handy here.

here is the code to get the login count from user_stats

 <?php  
  global $user  
 if(user_stats_get_stats('login_count',$user->uid) == 1){ //check that its user first time login  
 drupal_set_message("some message");  
 //do the stuff  
 }  
 ?>  

 
well you can use this module in many way for getting reg date much more..

well this come in very handy to solve my problem.