768x90 Getting Online Shouldn't be Tough- $7.49 .com Domains at Go Daddy

Step by step to deploy application using SVN and Capistrano

Here process deploying of application in a hosting (in this case i deploy my application in FastCGI on HostingRails.com). There are 3 major steps of deployment :


  1. Create SVN Repository (Next I will explain about GIT)
  2. Setup Capistrano & Deploy Application with Capistrano


Create SVN Repository

  • Create REPOSITORY to your hosting account, please ensure that your hosting is already installed capistrano & SVN or ask your hosting admin/support to install SVN and Capistrano.
username@mydomain.com [~]$ mkdir -p ~/svn/your_app_name
username@mydomain.com [~]$ svnadmin create ~/svn/your_app_name
username@mydomain.com [~]$ mkdir -p ~/tmp/your_app_name/{tags,branches,trunk}
username@mydomain.com [~]$ svn import ~/tmp/your_app_name file:///home/username/svn/your_app_name -m "Created Repository"

  • At this point you have enough setup on your Hosting account for single-user access to Subversion. You can now check out your repository at:
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk

  • Next we are going to add your existing Rails app to the Subversion repository. If you don't have an existing app, you will need to create one.
username@mydomain.com [~]$ svn co svn+ssh://username@mydomain.com/home/username/svn/your_app_name/trunk your_app_name_dev

  • Ok, it looks fine if you do right. The next step is copy your application for repository. Before this process, upload your existing application folder to your host in zip or tar.gz file. After uploaded, extract it to up folder of public_html (do not extract your application in public_html). After extracting, we will modify some data and permission file.

  • Your database.yml(.online) file simply needs to look like this:

production:
 adapter: mysql
 database: [your_hosting_username]_[your_database_name]
 username: [your_hosting_username] OR [your_hosting_username]_[your_database_name]
 password: your_password


  • And in your environment.rb(.online) file you'll just need to uncomment the following line to confirm you're in production mode:
ENV['RAILS_ENV'] ||= 'production'

  • Make sure your .htaccess file sends requests to dispatch.fcgi. Please Note - as of Rails 2.1.0 the .htaccess file no longer exists in the default skeleton.  Run a "rails _2.0.2_ testapp" and move over the public/.htacess from there.  This one is easy but also critically important.   In your local Rails application's public/.htaccess file change the :

RewriteRule ^(.*)$ dispatch.cgi [QSA,L]

  • EXACTLY where it is already in the file, don't change its position, to: 
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]

  • also - very important make sure the 'AddHandler fastcgi-script .fcgi' is commented out at the top of your .htaccess:  
    # General Apache options
    # AddHandler fastcgi-script .fcgi
    And that's it

  • Now look into public folder and edit all files with name "dispatch" (they are 3 files), edit the first line and change to :
#!/usr/local/bin/ruby

  • Do not forget to change permission into 755 for all files in public folder specially all dispatch.* files and .htaccess.

  • Next, you will need to copy your existing Rails app on your local machine into the version we just checked out
username@mydomain.com [~]$ cp -R your_app_name/* your_app_name_dev

  • Now you can see if Subversion recognizes the updated files and directories:
username@mydomain.com [~]$ cd your_app_name_dev
username@mydomain.com [~/your_app_name_dev]$ svn status

  • You should get something like this:

?      test
?      app
?      tmp
?      log
?      Rakefile
?      script
?      components
?      config
?      db
?      doc
?      lib
?      README
?      vendor
?      public


  • Now, just add them to the repository:

username@mydomain.com [~/your_app_name_dev]$ svn add test app tmp log Rakefile script components config db doc lib README vendor public

  • You will see a list of the files that were added with an 'A' next to indicating that the files will be added on the next commit. You will see something like this:

A         test
A         test/fixtures
A         test/fixtures/contact_mailer
A         test/fixtures/contact_mailer/notify
A         test/fixtures/contact_mailer/validate_email
A         test/fixtures/contacts.yml
A         test/functional
A         test/functional/website_controller_test.rb
A         test/integration
# and so on


  • Next, lets commit the Rails app to the repository
username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Added The Application"

  • This may take a few minutes depending on the size of your application. You will see the list of files appear again followed by this:
  • Transmitting file data .................................................................
    Committed revision 2.

  • Now your will be able to edit your code on your local machine and have the changes reflected in newer revisions simply by adding and committing files.


Setup Capistrano & Deploy Application


  • Setup your Rails application to work with Capistrano. Once you have checked out your code from the svn repository, change to the root of the Rails app on your development machine and run (look carefully there is a dot after capify command, just type it completely with a dot):

    username@mydomain.com [~/your_app_name_dev]$ capify .

    # This is the output
    [add] writing `./Capfile'
    [add] writing `./config/deploy.rb'
    [done] capified!
    Capistrano created two files: /config/deploy.rb and Capfile. (Note: /config/deploy.rb might have been skipped if you already had a deploy.rb file in your app.) The config/deploy.rb file will contain your application variables used to deploy your app, while the Capfile will contain your deployment tasks.


  • So open the deploy.rb file and we'll start customizing the deployment process. The first thing we want to do is set our application variables. So let's modify this first section of the file:

set :application, "your_app_name"   set :domain, "mydomain.com"  set :user, "username"        set :repository,  "svn+ssh://#{user}@#{domain}/home/#{user}/svn/#{application}/trunk"  set :use_sudo, false     set :deploy_to, "/home/#{user}/#{application}"   set :deploy_via, :checkout set :chmod755, "app config db lib public vendor script script/* public/disp*"  set :svn_username, "username" set :svn_password, "hosting_password" set :password, "hosting_password" default_run_options[:pty] = true ssh_options[:keys] = %w(/Path/To/id_rsa) role :app, "mydomain.com" role :web, "mydomain.com"
role :db, "mydomain.com", :primary => true

  • Now that everything is in place, you can commit your changes to the Subversion repository if you want:

    username@mydomain.com [~/your_app_name_dev]$ svn add config/deploy.rb Capfile
    username@mydomain.com [~/your_app_name_dev]$ svn commit -m "Configured application for Capistrano"

  • Last Step - Setup Your Hosting Account. Next we need to setup our Hosting account. This is where our hard work pays off with Capistrano. From your local machine enter the following commands:
username@mydomain.com [~/your_app_name_dev]$ cap setup


  • Next you need to run a cold deploy.

username@mydomain.com [~/your_app_name_dev]$  cap cold_deploy


  • Next we can do a full deploy

username@mydomain.com [~/your_app_name_dev]$  cap deploy


  • Or if you want Capistrano to run your migration files (be sure to have your database and database.yml setup properly).

username@mydomain.com [~/your_app_name_dev]$  cap deploy_with_migrations


  • If you ever run into problems and need to rollback to a previous revision of your code simple enter:

username@mydomain.com [~/your_app_name_dev]$  cap rollback


  • As you make revisions to your code on your local machine and are ready to deploy your updated application to the production server all you have to do is:

username@mydomain.com [~/your_app_name_dev]$ $ svn commit -m "Your Custom Reference Message";cap deploy


Case Abtractions [Indonesian Language]

Sorry for you guys, i write this article for my friends in my country, indonesia, to support their final thesis projects.


1. SPPK Pembelian Property atau Real Estate.

  • Description : Sistem ini ditujukan bagi user atau konsumen yang memiliki keinginan untuk membeli rumah namun memiliki pengetahuan terbatas tentang lokasi mana saja yang masih tersedia sesuai dengan keinginan mereka. Input user konsumen dapat berupa range budget atau harga yang di inginkan konsumen, luas tanah, luas bangunan, lokasi, dll. Diharapkan sistem ini dapat bekerja sama dengan para realestate group sehingga pengusaha realestate dapat menginputkan informasi tipe rumah, harga, lokasi, gambar rumah/design dan peta (dapat menggunakan peta dari google), harga basis investasi dapat didesign berdasartkan permintaan user developer untuk ditampilkan semakin meningkat berdasarkan periode waktu. Output bagi user konsumen adalah daftar real estate, diikuti dengan sublist informasi rumah yang masih tersedia (belum laku terjual) yang terdiri dari gambar rumah atau denah rumah, harga, dan detail property serta prediksi nilai investasi jika membeli rumah tersebut serta fasilitas anggunan yang ditawarkan developer jika tersedia.
  • Contoh www.propertyfinder.com
  • Skala user : masih dalam satu k0ta
  • Software Target: property group atau real estate group.
  • Tantangan: gunakan mushup google map untuk realtime peta jika tidak terdapat peta kota. Sistem dapat mendukung upload gambar atau video promosi jika diperlukan.
  • Teknologi basis web.

2. Event Management
  • sebagai salah satu contoh event management ditujukan untuk dosen universitas atau fakultas. Sistem ini dapat dikatakan sebagai perencanaan aktivitas dosen yang memudahkan mahasiswa untuk memantau keberadaan dosen untuk keperluan konsultasi. Dosen juga dapat memberikan keterangan terhadap jadwal konsultasi dan mahasiswa dapat mendaftar langsung untuk konsultasi, seperti pasien mendaftar dokter dirumah sakit, sehinga dosen dapat mengetahui siapa saja mahasiswa yang ingin berkonsultasi atau bertemu dengan dosen. Mahasiswa juga dapat memilih tanggal konsultasi dan jam yang diinginkan untuk bertemu dengan dosen, dosen akan menerima laporan berupa pesan pada halaman pribadinya. Output hampir mirip dengan kalender agenda dan email portal. untuk registrasi konsultasi fisik, system menampilkan daftar user pada tanggal tertentu berdasarkan urutan tanggal, deskripsi keperluan, dan nama mahasiswa.
  • Hal-hal yang dapat dilakukan : booking dosen, email portal, mahasiswa dan dosen, dapat upload dan download file dari email portal tersebut, calendar agenda.
  • Tantangan : dosen dapat menginput agenda dia melalui sms lalu event portal memprosesnya dan menampilkannya ke agenda event dan portal memberi report sms bahwa agenda telah dibentuk.
  • Contoh kasus lain sebagai perbandingan dapat dilihat disini : http://www.peoplecube.com/solutions-event-management.htm

3. Electric card or business card
  • Web ini ditujukan buat user yang ingin membuat kartu nama, kartu pos, atau poster, user dapat mengupload designnya untuk dicetak atau dijual memalui perantara yang punya website. owner website akan mengirim pesanan user jika telah selesai, pembayaran dapat berupa transfer bank.
  • Tantangan : sistem mendukung user mendesign sendiri postcardnya secara online atau mendesign ulang yang sudah jadi atau gunakan ajax dalam aplikasi ini.
  • kasus tidak hanya untuk kartu tapi dapat diganti dengan design baju online.
  • Contoh kasus : http://www.harboarts.com/shirtdesigner/productpage01.php
  • Tantangan : gunakan flex atau ajax untuk redesign atau design online

4. Web Operation System
  • Silahkan pelajari web ini : http://www.cloudcomputing.gopc.net/?gclid=CIr-xbi03pQCFQWxsgodJnu_SQ
  • Dapat diimplementasikan sebagai notebook untuk dosen atau mahasiswa, untuk menyimpan kuliah praktikum yang dpt dilakukan secara online, sehingga user dapat membuka kembali hasil praktikumnya diwarnet atau hasil kerja dan kuliahnya diwarnet.
  • Solusi : Gunakan Flex atau RJS atau AJAX.

5. Posyandu Online atau Apotik Online
  • Web ini serupa SPPK yang membantu user memilih obat berdasarkan penyakit yang dihadapinya atau ciri-ciri penyakit yang dihadapinya dan alergi user terhadap obat jika ada, output berupa daftar obat dan indikasinya serta aturan pemakaian.
  • Tantangan terhubung dengan apotik, artinya jika output obat sudah ditampilkan user dapat memesan langsung obat yang bersangkutan, dan obat dapat diantar. (lingkup hanya dalam kota saja.)

How to use find_by_sql without Model

many cases, we use model to use find_by_sql like ModelName.find_by_sql, but now how we can find_by_sql without mode?

ActiveRecord::Base.connection.execute 'select * from users'

To return array of hashes, you can use it :

ActiveRecord::Base.connection.select_all

.


Translation for your Ruby on Rails App



I am writing this article with accompanied by a cup of coffee while waiting MU Vs Chealsea for Champion Final. Back to the topic. You should know many familiar online translation like google and altavista. Now i will like to introduce you about gibberish in rails. Let start it :

  • Install the plugin to your app rails.
ruby script/plugin install http://svn.myutil.com/projects/plugins/gibberish_rails/
or
ruby script/plugin install svn://errtheblog.com/svn/plugins/gibberish
  • After that go to your Application_controller.rb then use arround_filter for implementation of gibberish :
class ApplicationController < ActionController::Base
around_filter :set_language

private
def set_language
Gibberish.use_language(session[:language]) { yield }
end
end
  • Another method is described in README file. Like :
class ApplicationController < ActionController::Base
around_filter :use_best_guess_locale

private
def use_best_guess_locale
session[:locale] = GibberishRails.best_guess_locale(params[:locale], request.env['HTTP_ACCEPT_LANGUAGE']) if ( ! session[:locale] || params[:locale] || RAILS_ENV == 'development' )

Gibberish.use_language(session[:locale]) {yield}
end
end
  • To create new dictionary, you can create it in YAML file such as es.yaml :
welcome_friend: ¡Recepción, amigo!
welcome_user: ¡Recepción, {user}!
love_rails: Amo los carriles.



_

Simple & Awesome Rails Form

How to create Simple, fast and awesome rails form in your rhtml or html.erb ? the answer for now is Super_In_Place_Controls & I tested in Rails 2.0. Let start to use it :

  • Install the plugin to your ruby app
ruby script/plugin install http://os.flvorful.com/svn/plugins/super_in_place_controls

  • In your layout or rhtml / html.erb put it :
<%= stylesheet_link_tag 'in_place_styles' %>

  • Done !!, let start to implement it in your view file (click the image below to enlarge).
  • For regular text_field you can change it to be :
in_place_text_field :product, :title

  • For regular text_area, you can change it to be :
in_place_text_area :product, :description

  • For regular select_tag, you can change it to be:
in_place_select :product, :product_type, :choices => %w(Awesomeness Coolness Phatness RubyBliss).map { |e| [e, e] }

  • For regular radio_collection, you can change it to be :
in_place_radio :product, :price, :choices => %w(199 299 399 499 599 699 799 899 999).map { |e| [e, e] }

  • For check box collection you can change it to be:
in_place_check_box :product, :category_ids, :choices => Category.find(:all).map { |e| [e.id, e.title] }, :display_text => :collection

  • And for date you can change to be :
in_place_date_select :product, :display_begin

  • for more style you can addcalendar_date_select_includes "blue" to the pages you want to use the calendar select on. The other styles for the calendar_date_select are "blue", "plain", "red", "silver", "default".

Create Realtime World News in Your Site

What could you do if you had access to the world’s news, and had a standardized and rational way to get quick responses to rich queries about what’s happening in the world? What could you build if you could incorporate dynamic, global, continually refreshed, high quality content into your applications, widgets, and websites? You should have many answers. But I have only 1 act, I will smileproudly. :D. Let's start to implement it by using Ruby on Rails:

  • Download this code and paste it to your app_name/lib folder
  • Then in your controller, put it :
require 'daylife'
a = Daylife::API.new('your api key','sharedsecret')
r = a.execute('search','getRelatedArticles', :query => 'sam adams', :limit => 5)
if(r.success?)
r.articles.each {|a| puts a.headline }
puts r.articles[1].source.daylife_url
else
# output the error message
puts "Error: #{r.code}: #{r.message}"
end
  • Now your dream comes true to have site like Yahoo News or at least like daylife.com
  • Has been tested and working nice :D

Snapshot Web Page trough Ruby

Some times, newbie question is valuable for me. Thanks for some one who asked about Snapshot a webpage in ruby by providing web url. Let see it :

  • Sign Up a free account HERE
  • Get Your API Key, after logged in.
  • Create a New File in your Model with name snapweb.rb, than paste code below inside :
require 'net/http'
require 'rubygems'
require 'xmlsimple'

class Snapweb

@@api_baseurl = 'http://webthumb.bluga.net/api.php'
@@api_key = 'fc52f8bdb9e5b86f8150a145d5c8fd97'

attr_accessor :collection_time, :job_id, :ok

def initialize(url, width = 1024, height = 768)
#for safety url you can uncomment it :
#url = url.gsub(/&/, '& a m p ;')
#please delete space in '& a m p ;'

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><request><url>#{url}</url><width>
#{width}</width><height>#{height}</height></request></webthumb>}

result = do_request(api_request)

if result.class == Net::HTTPOK
result_data = XmlSimple.xml_in(result.body)
@job_id = result_data['jobs'].first['job'].first['content']
@collection_time = Time.now.to_i + result_data['jobs'].first['job'].first['estimate'].to_i
@ok = true
else
@ok = false
end
end

def retrieve(size = :small)
api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><fetch><job>#{@job_id}</job><size>
#{size.to_s}</size></fetch></webthumb>}
result = do_request(api_request)
result.body
end

def retrieve_to_file(filename, size = :small)
File.new(filename, 'wb+').write(retrieve(size.to_s))
end

def ready?
return unless Time.now.to_i >= @collection_time

api_request = %Q{<webthumb><apikey>#{@@api_key}</apikey><status><job>#{@job_id}</job></status></webthumb>}
result = do_request(api_request)

if result.class == Net::HTTPOK
@ok = true
result_data = XmlSimple.xml_in(result.body)
begin
@result_url = result_data['jobStatus'].first['status'].first['pickup']
@completion_time = result_data['jobStatus'].first['status'].first['completionTime']
rescue
@collection_time += 60
return false
end
else
@ok = false
end

true
end

def ok?
@ok == true
end

def wait_until_ready
sleep 1 until ready?
end

private

def do_request(body)
api_url = URI.parse(@@api_baseurl)
request = Net::HTTP::Post.new(api_url.path)
request.body = body
Net::HTTP.new(api_url.host, api_url.port).start {|h| h.request(request) }
end
end

  • After that in your controller, put it :

class TeapociController < ApplicationController

def index

web_pict = Snapweb.new("http://teapoci.blogspot.com")

if web_pict.ok?
web_pict.wait_until_ready web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_1.jpg", :small)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_2.jpg", :medium)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_3.jpg", :medium2)
web_pict.retrieve_to_file("#{RAILS_ROOT}/public/images/teapoci_4.jpg", :large)

flash[:notice] = "Thumbnails saved"

else
flash[:notice] = "Error"
end

end
end

  • Now you have the screenshot images at folder /public/images/

Enjoy & Good Luck!!!

Thanks to : Josh

Live Validation Field with AJAX

LiveValidation is a small open source javascript library for making client-side validation quick, easy, and powerful. It comprises of two main parts. Firstly, it provides developers with a rich set of core validation methods, which can also be used outside the context of forms. Secondly, it provides your visitors with real-time validation information as they fill out forms, helping them to get it right first time, making the forms easier, quicker and less daunting to complete.

The naming conventions and parameters of the validations are similar to those found in the Ruby on Rails framework, and as such is the perfect client-side companion. Don’t worry if you dont use Ruby on Rails though, LiveValidation can be used anywhere you like, is simple to learn, and a joy to use.

Two versions are provided - a prototype.js version (ideal for use with Rails), and a standalone version (for using with any other javascript framework, or when having one at all would be overkill). Both are fully tested on most modern browsers with a comprehensive test suite.

So take a look around, download it, and make some forms (for) fun!

Check this out : LIVEVALIDATION.com

Random Characters in Ruby on Rails

  • AlphaNumeric Random Characters
>> chars = ("a".."z").to_a + ("1".."15").to_a
>> newpass = Array.new(8, '').collect{chars[rand(chars.size)]}.join
>> "8xa2b13f"

  • Another AlphaNumeric Random Characters
>> (1..8).map{ (0..?z).map(&:chr).grep(/[a-z\d]/i)[rand(62)]}.join
>> "JH789gfd"

  • ASCII Random Characters
>> (0..5).inject('') { |r, i| r << rand(93) + 33 }
>> "S#;og^"


Date and Time Functions in Ruby on Rails

This is implementation of Date and Time in Database (MySQL) into Ruby on Rail

Example:

BillPay.find(:all, :order => 'weekday(paid_at)' )
BillPay.find(:all, :select => 'day_of_year(paid_at) as "Days" ' )



Name Description
ADDDATE()(v4.1.1) Add dates
ADDTIME()(v4.1.1) Add time
CONVERT_TZ()(v4.1.3) Convert from one timezone to another
CURDATE() Return the current date
CURRENT_DATE(), CURRENT_DATE Synonyms for CURDATE()
CURRENT_TIME(), CURRENT_TIME Synonyms for CURTIME()
CURRENT_TIMESTAMP(), CURRENT_TIMESTAMP Synonyms for NOW()
CURTIME() Return the current time
DATE_ADD() Add two dates
DATE_FORMAT() Format date as specified
DATE_SUB() Subtract two dates
DATE()(v4.1.1) Extract the date part of a date or datetime expression
DATEDIFF()(v4.1.1) Subtract two dates
DAY()(v4.1.1) Synonym for DAYOFMONTH()
DAYNAME()(v4.1.21) Return the name of the weekday
DAYOFMONTH() Return the day of the month (1-31)
DAYOFWEEK() Return the weekday index of the argument
DAYOFYEAR() Return the day of the year (1-366)
EXTRACT Extract part of a date
FROM_DAYS() Convert a day number to a date
FROM_UNIXTIME() Format date as a UNIX timestamp
GET_FORMAT()(v4.1.1) Return a date format string
HOUR() Extract the hour
LAST_DAY(v4.1.1) Return the last day of the month for the argument
LOCALTIME(), LOCALTIME Synonym for NOW()
LOCALTIMESTAMP, LOCALTIMESTAMP()(v4.0.6) Synonym for NOW()
MAKEDATE()(v4.1.1) Create a date from the year and day of year
MAKETIME(v4.1.1) MAKETIME()
MICROSECOND()(v4.1.1) Return the microseconds from argument
MINUTE() Return the minute from the argument
MONTH() Return the month from the date passed
MONTHNAME()(v4.1.21) Return the name of the month
NOW() Return the current date and time
PERIOD_ADD() Add a period to a year-month
PERIOD_DIFF() Return the number of months between periods
QUARTER() Return the quarter from a date argument
SEC_TO_TIME() Converts seconds to 'HH:MM:SS' format
SECOND() Return the second (0-59)
STR_TO_DATE()(v4.1.1) Convert a string to a date
SUBDATE() When invoked with three arguments a synonym for DATE_SUB()
SUBTIME()(v4.1.1) Subtract times
SYSDATE() Return the time at which the function executes
TIME_FORMAT() Format as time
TIME_TO_SEC() Return the argument converted to seconds
TIME()(v4.1.1) Extract the time portion of the expression passed
TIMEDIFF()(v4.1.1) Subtract time
TIMESTAMP()(v4.1.1) With a single argument, this function returns the date or datetime expression. With two arguments, the sum of the arguments
TO_DAYS() Return the date argument converted to days
UNIX_TIMESTAMP() Return a UNIX timestamp
UTC_DATE()(v4.1.1) Return the current UTC date
UTC_TIME()(v4.1.1) Return the current UTC time
UTC_TIMESTAMP()(v4.1.1) Return the current UTC date and time
WEEK() Return the week number
WEEKDAY() Return the weekday index
WEEKOFYEAR()(v4.1.1) Return the calendar week of the date (1-53)
YEAR() Return the year
YEARWEEK() Return the year and week

link_to_file - Call File from .rhtml or .html.erb


  • Open app/helpers/application_helper.rb
  • Paste it :
def link_to_file(name, file, *args)

if file[0] != ?/
file = "#{@request.relative_url_root}/#{file}"
end

link_to name, file, *args

end

  • In your view, put it:
<%= link_to_file "teapoci file here", "teapoci.php" %>
.


Video Streaming in Ruby on Rails

Dream your application like youtube? First of all, this application is only working in UNIX Machine, and has not been tested to Windows. This article is taken from written of johndahl.

First, install the gem:

sudo gem install rvideo
.

Next, install ffmpeg and (possibly) other related libraries. This is documented elsewhere on the web, and can be a headache. If you are on a Mac, the Macports build is reasonably good (though not perfect). Install with:

sudo port install ffmpeg
.

Or, for a better build (recommended), add additional video- and audio-related libraries, like this:

sudo port install ffmpeg +lame +libogg +vorbis +faac +faad +xvid +x264 +a52
.

Most package management systems include a build of ffmpeg, but many include a poor build. So you may need to compile from scratch.

If you want to create Flash Video files, also install flvtool2:

sudo gem install flvtool2
.

Once ffmpeg and RVideo are installed, you’re set.

You should remember the basic commands of RVIDEO and here they are :

file = RVideo::Inspector.new(:file => "#{FILE_PATH}/filename.mp4")
file.video_codec # => mpeg4
file.audio_codec # => aac
file.resolution # => 320x240


command = "ffmpeg -i $input_file -vcodec xvid -s $resolution$ $output_file$"
options = {
:input_file => "#{FILE_PATH}/filename.mp4",
:output_file => "#{FILE_PATH}/processed_file.mp4",
:resolution => "640x480"
}

transcoder = RVideo::Transcoder.new

transcoder.execute(command, options)

transcoder.processed.video_codec # => xvid



------------------------------------------------------
DEMONSTRATION OR EXAMPLE OF USAGE
------------------------------------------------------

  • First Create file by uploading the video to your "#{APP_ROOT}/files/file_name.video_ext", you can use act_as_attachment to do it. Example your file is input.mp4.
  • Then in your controller you can run file inspector object like script below:
file = RVideo::Inspector.new(:file => "#{APP_ROOT}/files/input.mp4")

file = RVideo::Inspector.new(:raw_response => @existing_response)

file = RVideo::Inspector.new(:file => "#{APP_ROOT}/files/input.mp4", :ffmpeg_binary => "#{APP_ROOT}/bin/ffmpeg")

file.fps # => "29.97"
file.duration # => "00:05:23.4"

  • To transcode video, you should initialize a trancoder object :
transcoder = RVideo::Transcoder.new
.
  • Then pass a command and valid options to the execute method.
recipe = "ffmpeg -i $input_file$ -ar 22050 -ab 64 -f flv -r 29.97 -s"
recipe += " $resolution$ -y $output_file$"
recipe += "\nflvtool2 -U $output_file$"
begin
transcoder.execute(recipe, {:input_file => "/path/to/input.mp4",
:output_file => "/path/to/output.flv", :resolution => "640x360"})
rescue TranscoderError => e
puts "Unable to transcode file: #{e.class} - #{e.message}"
end

  • If the job succeeds, you can access the metadata of the input and output files with:
transcoder.original # RVideo::Inspector object
transcoder.processed # RVideo::Inspector object
  • Or you can use another Template for you View:
<% if video.processing_status == 2 %>
<div id="videoplayer<%= video.id %>">
<p>This item requires Macromedia Flash Player 7.</p>
<p>To get the latest version please <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" target="_blank">click here</a>.</p>
</div>
<script type="text/javascript">
var so = new SWFObject("/flash/vidplayer.swf?filePath=<%= url_for_file_column(video, 'file') %>.flv&thumbPath=<%= url_for_file_column(video, "file")%>.jpg", "vidplayer", "336", "326", "7", "");
so.addParam("menu", "false");
so.write("videoplayer<%= video.id %>");
</script>
<strong><%= video.title.titleize %></strong><br />
<%= video.body %><br/>
<%= link_to image_tag("icon_video.gif"), url_for_file_column(video, "file") %>
<%= link_to "download original", url_for_file_column(video, "file") %>
<% else %>
<strong><%= video.title.titleize %></strong><br />
<%= video.body %><br/>
<%= link_to image_tag("icon_video.gif"), url_for_file_column(video, "file") %>
<%= link_to "download original", url_for_file_column(video, "file") %>
<p>This video is still being converted, or else there has been some kind of error.</p>
<% end %>

  • Make it simple and never think as frustration then you will success.

That's all explanation about RVideo. You can use RMovie here.

Need a demo script?

 
powered by Blogger