Circular Arrays in Ruby

Ruby On Rails No Comments »

Circular Array In ruby

The main logic behind this post says that “How do we move through the array indices in a circular manner” i.e whenever we reach the last index the control should be transferred back to the first index and vice versa. I actally means to say the array should navigate like a circular linked list.

So,The example below will clarify its usage and the logic behind it.

In my case,  I had a query getting some values for me in an array.The task was to paginate the array based on each values or index of the array one at a time.i had tried wot the standard paginator bulit into ruby but it provided me with a little freaky control over the array for circular pagination.So i decide to write some own logic of mine for a for this particular pagination.

The below code tells us the story for having a circular pagination.

The line 1 is nothing but the method get person details which takes the parameter as the current user id which is displayed on the page.

The line 2 is the query whcih gets the data for me for the pagination purpose.

 In the line 3  I am initalizing a new array

The do loops extracts all the Ids present in the array and pushes those ids into the array @o_ids.

 Now, what the return does is, it takes the its takes in the parameter id  of the current user being displayed and first finds the index of that particular id in the array and then decrements the index by 1 to get the value previous to that index and finally resolves the values at the index using the at instance method of the Array class. The second values returned is nothing but the postion of the actual id coming as a parameter, and the third return values is the value next to the current id.In the third case I check that the incremented Id does not exceed the length which will inturn throw a nil error while pagination.So using the ternary operator it evaluate the id back to zero index whenver it exceeds the last index of the array making the array circular

For Example:

Imagine that the array @o_ids has the following values and the id of the current user that is been shown is 103 so the get_person_details get 103 as the parameter. The line 21 shows the output which is 102(id decremented from the current Id), the 103(current Id) and 104(the incremented Id)

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Robots in Rails

Ruby On Rails No Comments »

I use to wonder about the file robot.txt in the public folder of our rails app.So,I just really dived into it to find out what was actually up with it.

And I found that its been used to stop your pages or pages or certain restricted areas of your app from being indexed as well as accessed by the Robots or what we genearlly say as crawlers.These robots generally tend to traverse your webpage recursively to find the url been linked to the page and inturn traverse those urls also.

These Robots mainly come in 2 flavours.In my terms , I say the “THE GOOD ROBOT” and “THE EVIL ROBOT”.The example of “THE GOOD ROBOT” being the google bot which indexes my blog and makes it available in the search engine when anybosy searches something found in my blog.”THE EVIL ROBOT” Ican say a spamming robot which picks up my email address from blog and strats spamming me with some kinda unwanted mails.

So,How do I distinguish between the good and the evil and how do i tackle them?

 These robots can be distinguished and tackled in 2 best ways.

Way 1:Play with the /robot.txt file

         The robot.txt is kinda remote control to control the navigation access for a particular robot. Here what we gotta do is to use the following 2 simple parameters to control the robot navigation.

                1.User Agent:The user agent is generally the robot specification,like the name of the robot. For example, To have a common ploicy for all the robots visiting your site you can use the * as the user agent or if you want to deal  with a single robot say “BadBot” then you can use UserAgent : BadBot

        The second paramter that the file takes is the

                2.Disallow:Here we specify the directories or the locations in your app wherethe visiting robot should not be traversing or even try to access.For example, for making the whole app untraversable, we need use Disallow: / . Here the “/” defines the root of your app. In case if you want to restrict few directories from getting traversed you can use Disallow:/blog/admin/ which will restrict the robot from accessing the admin folder under the blog directory of the app.

Way 2: Use the META TAG

           Even the standard html META tag can be used to access control the robots

                    <META NAME=”ROBOTS”  CONTENT=”NOINDEX,NOFOLLOW”>

            Here the name attribute must be ROBOTS.You can’t really make it up with some robot name like google bot or badbot.Here you can change the content to vaarious combinations like “INDEX,NOFOLLOW” or “NOINDEX,”FOLLOW”

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Heroku-Play with your live Rails App

Ruby On Rails No Comments »

Heroku is become one of my role hero when developing at the app in the ,what we call as “LIVE” stage.Heroku changes your programming system around from an “OFFLINE” system to an “ONLINE” system.The onnly hard work that you need to achieve this is to go on the following link and sign up for your online programming enviornment.

     http://heroku.com/

 Heroku mainly features the following cool stuff for you:

    

  •      Instant Deployment.
  •      Create and Edit Online your files.
  •      Autogenerated full stack platform available for development.
  •      You can also share and collaborate your application.
  •      Import as well as Export your apps.
  •      One click Ruby gem Installer.
  •      Keep an eye on your app through the rails console.
  •      Painlessly migrate your database schemata.

For live videos and demos of heroku do visit:

          http://heroku.com/features

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Playing Flv Files in Ruby On Rails (Part 3)

Ruby On Rails No Comments »

Taking screenshots of the uploaded video using the FFMPEG Plugin 

Hey, now its time to take photos from your uploaded videos…I hope that sounds good

 

Anyways,It will be a simple job if you have achieved success in integrating the mencoder into the app.

 

So,lets start talking about the FFMPEG encoder.The FFMPEG encoder works similar to the Mencoder utility.But,the only difference is that it provides more control over the video.It provides the image capturing facilty which techies generally call screenshots.

Using the FFMPEG utility we can generate screenshots of various sizes and also develop thumbnails for our rails app.

 

In order to download the FFMPEG utilty,check the following link

 

http://www.free-codecs.com/ffmpegGUI_download.htm

or

http://www.videohelp.com/tools/ffmpeg

 

Then u just have to copy the files from the unzipped folder into the mplayer folder in the public directory of our application.

 

For the documentation with respect to the usage of the ffmpeg codec please visit the following site:

 

http://ffmpeg.mplayerhq.hu/documentation.html

The following function takes the responsibility of generating the screenshots of the uploaded video

def self.grab_screenshot_from_video(path,name,video_id)

      memdir = RAILS_ROOT+’/public/mplayer/’

      opdir = RAILS_ROOT + “/#{video_id}/”+name

      jpgdir =RAILS_ROOT + “/#{video_id}/”+name

      #conversion to mencoder format

      system “#{memdir}ffmpeg -i #{opdir}.flv -s 320×240 -vframes 1 -f image2 -an #{jpgdir}.jpg”

   end

 

The grab_screenshot_from_video takes the path of the generated video as the input and passes the video to the FFMPEG commandline utility to generate an image of size 320×240 and then saves the image in the jppdir.

 

NOTE:

 Here I have placed the FFMPEG utilty in the mplayer directory in thr public folder of our app.

Please do read at the following section reagarding the compatibility and testing of the FFMPEG encoderhttp://ffmpeg.mplayerhq.hu/compat.html

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

Playing Flv Files in Ruby On Rails (Part 2)

Ruby On Rails No Comments »

Assuming the basic stuff in our hands, we can  now move on to the development of the flash video playback

 

The basic functionality of the  video app has been defined with the following inputs and outputs:

The user uploads the video using the user interface

The video is then converted into the flv format using the mencoder command line converter

The converted video is then played in the flv player in the browser output.

 

So, lets start off with the database stuff,the following is the basic structure of the database which I have been using for the demo

Just Posting the migration file.

 

class CreateVideos < ActiveRecord::Migration

  def self.up

    create_table :videos do |t|

      t.column :video_data, :string

    end

  end

 

  def self.down

    drop_table :videos

  end

 

end

This is  just a basic database which saves the video_name and the id of the video.You can customize this file to save more info related to the video.

 

 

Now,First of all, I generate a controller named Upload Controller which handles the basic actions for video conversion

 

FileName:upload_controller.rb

 

class UploadController < ApplicationController

 

 

  def convert

    render :file => ‘app/views/upload/convert.rhtml’

  end

 

The convert action render the input file for the video i.e  the webpage from the video is supposed to be uploaded.

 

 

 

  def show_video

  if request.get?

      @video = Video.new

    else

      @video = Video.new(params[:video])

      if @video.save

      upload = Video.convert_to_flv(@video)

      @file_data = Video.find(:first, :select=>’DISTINCT id,video_data’,:conditions =>[’video_data=?’,@video[”video_data”]],:order => “id DESC”)

      @video_data= “/video/video_data/”+ “#{@file_data[”id”].to_s }/”+ “#{@file_data[”video_data”]}.flv”      

flash[:notice]=”Hey,Your video has been uploaded successfully”

       render :file => ‘app/views/upload/show_video.rhtml’

    else

      flash[:notice]=”Hey,There was an error processing your video”

  end

  end

end

end

 

The show video is the action which handles the conversion of the input video and also the display of the video to the output page.

The action receives the parameters named video from the input page and before saving the video converts the video to the flv format

The convert_to_flv takes the @video as the parameter and converts it into the flv format which we will see later.

The @file data is nothing but a result set which holds the data of the query which gets the information related to the latest uploaded video by the user.

The @video_data passes the path to the video  to the output flv player

 

FileName: convert.rb

 

<%= form_tag({:action=>’show_video’},{:multipart=>true}) %>

    <%=file_column_field(”video”,”video_data”,:size=>”15″)%>

</p>

    <p>

      <input name=”convert_submit” type=”submit” value=”Convert_submit” id=”convert”>

    </p>

<%=end_form_tag%>

 

 

Here I am using the file column plugin to upload the video and the form action pointing to the action show_video

 

FileName: show_video.rb

 

<%= javascript_include_tag ‘ufo’ %>

<h> Show Video </h></br>

<%=flash[:notice]%>

<% p “video data from the view”%>

<% p @video_data%>

<%=flv_player :file =>@video_data %>

 

 

The show video represents the output file of the flv player.The Javascript include tag includes the ufo.js which comes bundled with the flash player helper plugin and  needs to be explicitly included in your application.

NOTE: The ufo.js can be included to application.rb when it comes to a development of the big app.

The flv_player tag adds an flv player to the page with the input.For more customization with respect to the player You can visit the farooq ali’s blog  which I have mentioned in my previous post.

 

Now the last and the most important, The model file

 

FileName:Video.rb

 

class Video < ActiveRecord::Base

  file_column :video_data

 

  def self.convert_to_flv(upload)

      full_name =  upload.video_data

      name_array = full_name.split(”/”)

       name = name_array[name_array.length-1]

      directory = “public/video/video_data/#{upload.id}”

    # create the file path

        path = File.join(directory, name)

      if !name.nil?

        convert_video_to_flv(path,name, directory)

      end

    end

 

The convert_to_flv takes the input video and strips out the filename from the parameter and creates a directory under the directory path given above with the id  and saves the uploaded file there.

The uploaded file is then passed to the convert_video_yo_flv method which we will see below.

 

 

 

  def self.convert_video_to_flv(path,name,video_id)

      memdir =RAILS_ROOT + ‘/public/mplayer/’

      opdir = RAILS_ROOT + “/#{video_id}/”+name+”.flv”

      filepath = RAILS_ROOT + “/#{video_id}/”+name

      system “#{memdir}mencoder #{filepath} -o #{opdir} -of lavf -oac mp3lame -lameopts abr:br=56 -srate 22050 -ovc lavc -lavcopts vcodec=flv:vbitrate=500:mbd=2:mv0:trell:v4mv:cbp:last_pred=3 -lavfopts i_certify_that_my_video_stream_does_not_use_b_frames”

      File.delete(”#{filepath}”)

    end

end

 

The convert_video_to_flv  takes the path, name and the video_id as the parameter and then uses the  mencoder command line utility to convert the video to flv format.

And then deletes the original file after conversion ,which the user has uploaded ,mainly to save the server space.

 

I am also posting the following links with respect to the mencoder command which will help u take more control over the commanline

HOWTO Mencoder Introduction Guide

http://gentoo-wiki.com/HOWTO_Mencoder_Introduction_Guide

 

Basic usage of Mencoder

http://www.mplayerhq.hu/DOCS/HTML/en/mencoder.html

 

Encoding with the libavcodec codec family

http://www.mplayerhq.hu/DOCS/HTML/en/menc-feat-enc-libavcodec.html

 

Now,Before I hang up this post of mine, I would like mention a few checkpoints with respect to the conversion and  the code also.

 

  1. The code if mine can be still refactored by keeping the model loose and placing the methods from to the upload_helper in your app and then calling those method conveniently before save.
  2. During the conversion of 3gp file to flv format, it may  happen that the video may not play the sound.This is mainly because of the AMR sound codec,I have been working on this issue and will soon post the resolution as the AMR codec is been integrated with the mplayer.

 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • blogmarks
  • Book.mark.hu
  • co.mments
  • Technorati
  • YahooMyWeb
  • IndianPad
  • DZone

WordPress Theme & Icons by N.Design Studio. Packaged by Edublogs - education blogs.
Entries RSS Comments RSS Login