Create Game in Air or Flex Easily

I am the admirer of bored.com website, this site will help you with its games to reduce your stressing in office or work. But How you can create your own game in Flex or Adobe air with painless ? I have found a great library to help developer in making 2D game easily, it is called FlashPunk by Paul Sztajer. Thanks dude.

FlashPunk is a free ActionScript 3 library designed for developing 2D Flash games. It provides you with a fast, clean framework to prototype and develop your games in. This means that most of the dirty work (timestep, animation, input, and collision to name a few) is already coded for you and ready to go, giving you more time and energy to concentrate on the design and testing of your game.

This framework is designed for use with the free Flex framework, used for building Flash applications; by combining this with a code editor such as FlashDevelop or Flash Builder, you can import the FlashPunk library and develop games without the need of the official Flash IDE.

You can feel the delicious of features:
  • Framerate-independent and fixed-framerate timestep support.
  • Fast & manageable rectangle, pixel, and grid collision system.
  • Helper classes for animations, tilemaps, text, backdrops, and more.
  • Debug console for real-time debugging and information tracking.
  • Sound effect support with volume, panning, and fading/crossfading.
  • Powerful motion tweening for linear, curved, and path-based movement.
  • Z-sorted render lists for easy depth management.
  • Simple keyboard and mouse input state checking.
  • Quick & efficent particle effects and emitters.
Click here to see flashPunk sample game which is not for flex or flash but it is already used for android.

Download Youtube Video Using ActionScript or Air

Youtube is my favorite website and very entertaining, not only in video but also making money. How you can download youtube video to flv format? A week ago, i have little experiment to make Air application for downloading Youtube. The important thing you have to get is the video id http://www.youtube.com/watch?v=yGTg5116dCM, the action script is very simple, even you can make multiple download as many as you want, here is the script:

private function configureListeners(stream:URLStream):void {
    var _date:Date = new Date();
    var _fileName:String = String(_date.milliseconds)+".flv";
    stream.addEventListener(Event.COMPLETE, function(event:Event):void {
      var fileData:ByteArray = new ByteArray();
      stream.readBytes(fileData,0,stream.bytesAvailable);
      var file:File = File.documentsDirectory.resolvePath(_fileName);
      var fileStream:FileStream = new FileStream();
      fileStream.open(file, FileMode.WRITE);
      fileStream.writeBytes(fileData,0,fileData.length);
      fileStream.close();
     });
    downloadProgress.source = stream; //downloadProgress is ProgressBar id    
  }
  
  public static const GET_VIDEO_INFO :String = "http://youtube.com/get_video_info.php";
            
  public function downloadVideo(_youtubeId:String):void{
    var service :HTTPService = new HTTPService();
    service.url = GET_VIDEO_INFO + "?video_id=" + _youtubeId;
    service.resultFormat = 'object';  

    service.addEventListener(ResultEvent.RESULT, function(evt:ResultEvent):void{
      var request:URLRequest = new URLRequest(unescape(evt.result.toString()).split("|")[1]);
      var stream:URLStream = new URLStream;
      configureListeners(stream);
       try {
         stream.load(request);
       } catch (error:Error) {
         trace("Unable to load requested URL.");
       }
     });
     service.send();
    }

Yeah, that is a short codes, for advance application you can use as3youtubelib to search, subscribe and comment the video. I have used oauth google and youtube API for multiple uploads to youtube. And once again no webservice unless google data protocol. i use pinless oauth. Please read the previous article. Thank you.

Sort Collection Rss By PubDate in ActionScript

XML can be friendly and some times can be nightmare for me. A few days ago, i have task to sort rss results from multiple sites by the pubDate. If you see the source xml of rss, each websites has common format pubDate : Wed, 03 Nov 2010 22:31:34 +0000 . As my experience, converting string date to datetime in actionScript using DateField.stringToDate not always give you actual result and my client want get the results are sorted up to milliseconds. There are some suggestion to use XSLT to sort xml by pubDate, but my application is desktop Air, how to do that without connect to webservice and parsing the rss result to XSLT ?

ActionScript is very fast to recursive big of data. So I decide to sort rss results in XMLListCollection, here is my codes:

//_result are composite of total rss results from a number of websites.
    // _results += new XMLList(XML(event.result)..item);
    public function sortRss(_results:XMLList, sortedResults:XMLListCollection):void{
      var sort:Sort = new Sort();
      sortedResults = new XMLListCollection(_results);
          
      var sortField:SortField = new SortField();
      sortField.compareFunction = sortRssByDate;
      sortField.descending = true;
     sort.fields = [sortField]
           
      sortedResults.sort = sort;
      sortedResults.refresh();
    }
    
    public var months:Array = new Array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec');

    private function convertPubDate(_pubDate:String):Date{
      var arrDate:Array = _pubDate.split(/\s/gi);
      var _strDate:String = arrDate[0]+" "+arrDate[1]+" "+arrDate[2]+" "+arrDate[3];
      var arrTime:Array = arrDate.length > 5 ? String(arrDate[4]).split(/\:/gi) : [];        
      var _hour:Number = arrTime.length == 3 ? Number(arrTime[0]) : 0;
      var _minute:Number = arrTime.length == 3 ? Number(arrTime[1]) : 0;
      var _second:Number = arrTime.length == 3 ? Number(arrTime[2]) : 0;
      var _dateTime:Date = new Date(Number(arrDate[3]), months.indexOf(arrDate[2]),Number(arrDate[1]),_hour,_minute,_second);
      return _dateTime;
    }
      
    private function sortRssByDate(itemA:Object,itemB:Object,fields:Array = null):int{
    var dateA:Date = convertPubDate(itemA.pubDate);
      var dateB:Date = convertPubDate(itemB.pubDate);
      return ObjectUtil.dateCompare(dateA,dateB);
  }

Finally, it works without crash the application. I have tested from 10 websites with 25 items for each rss per 1 box, and i have 10 boxes. Total 100 websites rss that have to be sorted together by pubdate and grand total item is 2500 items.

BBAuth, Y!Oauth with pinless authentication in Air

I developed Air application which requires yahoo profile data. I think the application is little bit extraordinary since it doesn't need webservice, because my client won't it. I found Yahoo SDK for AS3 to build simple Yahoo Social Applications. It is quite satisfied to introduce me how to use Browser-Based Authentication (BBAuth) or Yahoo! Oauth, but how to make it not to open external browser and automatically get access token without invoking webservice and get verification pin? I got inspiration from twitter pinless . Fortunately, it works, you can see my screencast below:



When you click "Login To Yahoo" button, the authorize() method is executed, below is the codes.

private function authorize():void{
        YSession = new YahooSession(StormModel.YCONSUMER_KEY, StormModel.YSECRET_KEY, StormModel.YAPPLICATION_ID);
        YSession.clearSession();
        YSession.auth.addEventListener(YahooResultEvent.GET_REQUEST_TOKEN_SUCCESS, handleRequestTokenSuccess);
        YSession.auth.addEventListener(YahooResultEvent.GET_ACCESS_TOKEN_SUCCESS, handleAccessTokenSuccess);
        YSession.auth.pinlessAuth = true;
        
        var rect:Rectangle = new Rectangle(50,50, 780, 500);
        var browser:CustomHtmlHost = new CustomHtmlHost;
        var newHTMLOptoions:HTMLWindowCreateOptions = new HTMLWindowCreateOptions;
        newHTMLOptoions.x = 50;
        newHTMLOptoions.y = 50;
        newHTMLOptoions.scrollBarsVisible = true;   
        htmlBox = browser.createWindow(newHTMLOptoions);
        YSession.auth.htmlLoader = htmlBox;
       YSession.auth.getRequestToken("http://www.google.com");
      }
      
      private function handleRequestTokenSuccess(event:YahooResultEvent):void{
       YSession.auth.sendToAuthorization(event.data as OAuthToken);
      }
      
      private function handleAccessTokenSuccess(event:YahooResultEvent):void{
        YSession.auth.token = event.data as OAuthToken;
        htmlBox.stage.nativeWindow.close();
        YSession.setAccessToken(event.data as OAuthToken);
        gridProviders.addItem({token: YSession.auth.token.key, secret: YSession.auth.token.secret});
      }

The screencast seems little fool, because i use callback to www.google.com, but you can use any redirect url, eg: to your webservice, your domain or yahoo.com. Aside issues, to make my pinless authentication work sexier, I should hacks some line codes in YahooSession.as and AuthorizationRequest.as . (You can copy paste from these links). After i get the accessToken and accessSecret, i store them in sharedObject, and then re-validate any time you want extend the expired token. So what is CustomHtmlHost? Adobe has changed the policy for HTML where HTMLLoader is no available if you create directly new HTMLLoader, it is little hack solution from me:

package com.yahooStorm.utilities
{
    import flash.display.NativeWindowInitOptions;
    import flash.events.Event;
    import flash.geom.Rectangle;
    import flash.html.*;

    public class CustomHtmlHost extends HTMLHost
    {
        import flash.html.*;
        
        public function CustomHtmlHost():void{}
        
        override public function 
            createWindow(windowCreateOptions:HTMLWindowCreateOptions):HTMLLoader
        {
            var initOptions:NativeWindowInitOptions = new NativeWindowInitOptions();
            var bounds:Rectangle = new Rectangle(windowCreateOptions.x,
                                                 windowCreateOptions.y, 
                                                 1000,
                                                 650);
            var htmlControl:HTMLLoader = HTMLLoader.createRootWindow(true, initOptions,
                                        windowCreateOptions.scrollBarsVisible,bounds);

            htmlControl.addEventListener(Event.COMPLETE, onCompleteWindowHandler); 
            return htmlControl;
        }
        
        public function makeWindow(options:HTMLWindowCreateOptions):HTMLLoader{
          return createWindow(options)
        }
        
        public function onCompleteWindowHandler(event:Event):void{
        }
        
        override public function windowClose():void
        {
            htmlLoader.stage.nativeWindow.close();
        }
        
        override public function updateTitle(title:String):void
        {
          htmlLoader.stage.nativeWindow.title = "Placepoint Browser: " + title;
        }
    }
}

I am very interested to make BBauth pinless version work too in Flex and Flash As3 and then build the package scripts to swc, but i still have no time to do that, ASAP i will post the swc and documentation here.

If there's any question or suggestion please post in the comment box. Thank you.

ArrayCollection Mapping From Multiple Object Types

 private function listToString(element:*, index:int, arr:Array):String {
   var _return:String = "";
   if(element is FeedInfo){ 
     _return = element.address;
   }else if(element is UserFeed){
     _return = element.name;
   }else{
     _return = element.id;
   }
    return _return;
 }
    
 private function prepareSaveFeeds(_list:RxCollection):void{
   var _tmpUserFeed:UserFeed = new UserFeed;
   _tmpUserFeed.feedAccount = _account;
   _tmpUserFeed.user = userModel.currentUser;
   _tmpUserFeed.keywords = _list.toArray().map(listToString).join("::");
 }

The output will be

 "yacobus::reinhart::blog"

BackUp PostgreSQL in CommandLine

pg_dump -h db_host -U user_name db_name > dump_file.sql

And Restore by:

psql -h db_host -U user_name -d db_name -f dumpfilename.sql

HTML5 For Client Architectures and Virtualization Loom

Such trends as cloud computing, service oriented architecture (SOA), social media, software as a service (SaaS), and virtualization are combining and overlapping to upset the client landscape. If more of what more users are doing with their clients involves services, then shouldn't the client be more services ready? Should we expect one client to do it all very well, or do we need to think more about specialized clients that might be configured on the fly?

Today's clients are more tied to the past than the future, where one size fits all. Most clients consist of a handful of entrenched PC platforms, a handful of established web browsers, and a handful of PC-like smartphones. But, what has become popular on the server, virtualization, is taken to its full potential on these edge devices. New types of dynamic and task specific client types might emerge.

Imagine that you have your own personal Windows OS, that maybe you have signed up for Microsoft’s new Intune service to manage that from the cloud standpoint. Then, you have another Google OS that comes down with applications that are specific from that Google service, and that desktop is running in parallel with Windows, because it’s fully controlled from a cloud provider like Google. Something like Chrome OS is truly a cloud-based OS, where everything is supposed to be stored up in the cloud.

Those kinds of services, in turn, can converge into the PC, and virtualization can take that to the next level on the endpoint, so that those two things don’t overlap with each other, and a level of service, which is important for the cloud, certainly for service level agreements (SLAs), can truly be attained. There will be a lot of flexibility there.

Virtualization is a key enabler into that, and is going to open up PC architectures to a whole brave new world of management and security. And, at a platform level, there will be things that we're not even seeing yet, things that developers can think of, because they have options to now run applications and agents and not be bound to just Windows itself. I think it’s going to be very interesting.

 When we talk about the client, we're mostly thinking about the web-browser based client as opposed to the client as an entire virtualized OS. When you're using a business process management system (BPMS) and you involve people, at some point somebody is going to need to pull work off of a work list and work on it and then eventually complete it and go and get the next piece of work.

That’s done in a web-based environment, which isn’t particularly unusual. It's a fairly rich environment, which is something that a lot of applications are going to. Web-based applications are going to a rich Internet application (RIA) style.

We have tried to take it even a step further and have taken advantage of the fact that by moving to some of these real infrastructures, you can do not just some of the presentation tier of an application on the client. You can do the entire presentation tier on the web browser client and have its communication to the server, instead of being traditional HTML, have the entire presentation on the browser. Its communication uses more of a web-service approach and going directly into the services tier on the server. That server can be in a private cloud or, potentially, a public cloud.

What's interesting is that by not having to install anything on the client, as with any of these discussions we are talking about, that's an advantage, but also on the server, not having to have a different presentation tier that's separate from your services tier.

You go directly from your browser client into the services tier on the server, and it just decreases the overall complexity of the entire system. That's possible, because we base it on Ajax, with JavaScript that uses a library that's becoming a de-facto standard called jQuery. jQuery has the power to communicate with the server and then do all of the presentation logic locally.

Next Rich Internet Application of Web Base will be more interactive using HTML5, let's wait up to HTML5 finish the Virtualization on the next release.

How To Upgrade to Rails 3 of your old rails project

A few days ago i was concerning to upgrade my rails 2.3.3 to 3.0.0.beta for my application, but now it is rails.3.0.0.beta4, first thing you do is upgrading your ruby version to 1.8.7 or higher and then installing all requirements gems before upgrading to rails 3. ( If you love audio visual, you can skip the steps below and download the screencast. )





gem install tzinfo builder memcache-client rack rack-test rack-mount 
gem install erubis mail text-format thor bundler i18n
gem install rails --pre

Looks like simple right? Don't be happy because you will face lot of troubles after this, at your first experience. In this case i am using Windows OS. Let's call your application name is reinhartlab , first thing i do is creating new blank rails3 application:

rails new reinhartlab3 -v3.0.0.beta4

or you can clone rails project by git clone git://github.com/rails/rails.git after that copy paste folders : app, db, test, vendor, lib and file config/database.yml. to reinhartlab3

Now is the credential information you should take care.

Install a gem for sync your old project to rails 3 project:
gem install rails-upgrade
and then
rake -T rails:upgrade

Backup your code that want be upgraded to Rails 3, now go to reinhartlab and do backup:
rake rails:upgrade:backup

now check your old rails configuration for compatible with Rails 3

rake rails:upgrade:check
Just follow the advices which will be provided on results, after that copy paste your reinhartlab/config/routes.rb and reinhartlab/config/application.rb to your reinhartlab3/config and all your changed files to new project rails 3

Now the final hard steps is gems management. In your project root you will see Gemfile , copy paste all your gem.confing in your reinhartlab/config/environment.rb to Gemfile and then follow the correct structure of written. If you are done with them, now let bundle your gem.

bundle install

Now the final step is running your new rails application by :

ruby script/rails server

PS: Rails3 has many new rules in routes and model, if you use name_scope, you should modify it manually in your model, the rakes-upgrade should tell you how to fix it and the link to learn them, i think google is a nice short cut for people who hate doing RTFM.Click the image below to see my first upgrade to rails3. The upgrading and installation are easy, but sync your gems and plugins to Rails3 will hurt you a half death. So happy headache with sync gems hehehe ...

Click me to see my Gemfile

source 'http://rubygems.org'

gem 'rails', '3.0.0.beta4'

gem 'sqlite3-ruby', :require => 'sqlite3'

gem "authlogic", :git => "git://github.com/odorcicd/authlogic.git", :branch => "rails3"

gem "will_paginate", :git => "git://github.com/mislav/will_paginate.git", :branch => "rails3" 

gem 'fastercsv', '>= 1.5.1'
gem 'ruby-gmail', '>= 0.0.8'
gem 'restfulx'
gem 'gdata'
gem 'oauth'
gem 'mail'




Dont Add your Gmail Inbox To Public Bookmark

If you have added the web address (URL) of your Gmail inbox to your browser bookmarks, make sure that the bookmarks are not getting synched with a public service like Delicious or Google Bookmarks.

Gmail Inbox

That’s because when you bookmark your Inbox or any other folder in Gmail, your email address is added to the title of the bookmark. When this bookmark becomes public, your email address automatically gets exposed to spam bots.

This may sound like an obvious thing but just search for “mail.google.com” or “Gmail Inbox” on Delicous, Xmarks or even Google Bookmarks and you’ll tons of “working” email addresses in the title of the bookmarks.

Forget iPhone 4, Buy new Mac Mini



iphone4Today's WWDC speech by Steve Jobs was in some ways, surprising. Despite a veritable armful of rumors, Steve mainly talked about a handful of tech, with emphasis on the new iPhone 4. So what did he leave out, and when may it come true anyway?

New Mac Minis

mac-mini-hdmiThe Mac Mini is a much-beloved little computer, widely use as a home theater device and even as a server workhorse (due to its petite size and reasonable pricing). So why didn't Apple lavish any WWDC love on their smallest Mac? Strong rumors hinted at a big refresh with HDMI connectivity, after all.
Because the Mini is not a high profile world-beating device, like the iPhone or iPad, it's not high on Apple's priority list and simply isn't going to garner many headlines online or in the traditional press. Apple probably didn't want to water down the excitement about the iPhone 4 by announcing other new hardware. (Leaks have already muffled a bit of the thunder around the new iPhone as it is.)
When will we hear this news? Soon. We think it'll happen, and Apple will just slip out a special press release with some Jobs quotes and a splashy new Web page to advertise it.

HTML5, in the shadows
Jobs did mention HTML5 briefly during his address. But it was literally a mention in passing, and he didn't even play up the new promotional HTML5-ready Apple demo page. Instead Jobs noted HTML5 is one "platform" the company supports, an "open, uncontrolled platform that is forged and defined by standards alone." Apple is "fully behind" it, and its browsers are "in the lead" in supporting it. Apple's second platform is the "curated" iPhone OS (now iOS) for comparison.
Will Apple hit the news with HTML5? Possibly not in a special event, unless you're talking about a dedicated Jobs blog. Apple thinks its support for HTML5 is now self-sustaining in terms of news and media coverage, and probably didn't want to bring any hint of the Apple versus Adobe "war" into the Apple WWDC event.

iTunes in the cloud
Not a peep about iTunes during Steve's speech, which may be a surprise to some who were expecting news about a move to cloud-based storage and content streaming (possibly using tech from Lala, the streaming music platform that Apple recently acquired). The only mention of iTunes is in the new iPhone's specs page on Apple.com, where it's noted the device needs "iTunes 9.2" whereas the current version is 9.1.1.
Will iTunes 9.2 have cloud elements? We don't know. It'll have to ship before the new iPhone 4 goes on sale on June 24th, so it has to happen soon. We suspect a cloud-based iTunes would be a big enough revelation that Jobs would mention it in a big event so it won't appear in June. But it may merit a special "Come Feel Music's Future in the Air" Apple-style special event later this year.

MacBook Air revisions
Intel's got new silicon on the way that'll give Mac's slenderest model a big boost, and it's a premium piece of tech for Apple--they'll definitely support it through a basic spec upgrade.
When will the Air laptop get some love? Soon. Probably on a Tuesday, Apple's traditional new hardware launch day, as a minor mention in a press release.

External trackpad, the "Magic Slate"?
Many folk will have been saddened to not see this announced today--it's a device that'll surely sell by the boatload, thanks to Apple's marketing and impressive lead in multitouch technology. But the rumors about it today did reveal the "leaked" hardware had a copyright sign from 2009, so they may have been of a prototype, rather than shipping hardware.
When will the Slate go on sale? Sometime this year, we hope. If it does, we're guessing around October, a year after the Magic Mouse came out, as the two peripherals are kinda complementary.

Safari 5, OS X 10.6.4
Kinda surprising that these two "flagship" pieces of code didn't get much of a mention at Apple's developer conference. But maybe Apple's already supremely confident in its software offerings and doesn't feel the need to advertise single-point code updates. And don't forget Apple will be revealing more stuff to developers throughout this week's WWDC sessions.
Maybe Safari 5 and the new OS X tweak will get a proper "private" reveal to devs this week and a quiet launch soon.

UPDATE: In an email sent hours after the keynote, Apple announced the release of Safari 5 today.
Free MobileMe
Hmmm. We're scratching our heads on this one, as a free user level in MobileMe would be such a powerful boost to the iPhone's already prodigious powers. Maybe Apple's not got all its code in order yet, as they've been too busy messing with iPhone 4s, iPads and new versions of OS X and Safari.
Will we see this? Yes, we think so. But possibly as a big mention during another hardware/software release later in the year.

iPhone 4's HD video output powers
So here's something you probably didn't know, as it's not surfaced yet online: One thing Steve didn't mention is that the new iPhone outputs 720p-resolution video over a 30-pin to VGA connector cable, meaning it can drive your HDTV with HD-quality video. That beats the existing standard-def resolution, and almost rivals the existing Apple TV's powers.
Does this hint at a 1080p-capable Apple TV revamp? Very possibly, if you apply some twisty logic about why Apple didn't highlight this power.

Source: fastcompany.com

Is Apple TV 16GB with OS iPhone 4 released?


Alleged details on a forthcoming update to the Apple TV set top box were revealed on Friday, with the device reportedly based on iPhone OS 4, powered by Apple's custom-built A4 processor, and offering 1080P cloud-based streaming content -- all starting at just $99.

Engadget editor Joshua Topolsky said the information came from a tip and was confirmed by a source "very close to Apple." The new hardware will reportedly have just 16GB of storage, but will be capable of full 1080P HD video with 99$ only.

"Not only will this be priced to sell (like hotcakes), it seems that Apple is moving away from the model of local storage and will be focusing the new ATV on cloud-based storage (not unlike Amazon's streaming scheme, though we're talking instant-on 1080P, a la Microsoft)," the report said. "For those still interested in keeping their content close, there will be an option to utilize a Time Capsule as an external storage component, but the main course will be about streaming."

The new hardware, said to be small with only a power plug and video out, was described as "an iPhone without a screen." Sources could not say whether or not the new hardware would be compatible with software from the App Store, though Topolsky noted "it makes sense given the shared platform."

Engadget reported that Apple will not announce the new hardware at the forthcoming Worldwide Developers Conference, but the development is currently "full steam ahead."

The project has allegedly been in development since long before the Google TV was introduced last week. Google's offering will run on the Android operating system, and will be integrated in set top boxes as well as on HDTV hardware itself from major manufacturers. Google TV, which will run applications from the Android Market and stream Internet video, is scheduled to be released this fall.

Currently, the Apple TV costs $229 and comes with 160GB of storage. Last September, Apple discontinued the low-end 40GB Apple TV.

The set top box software was updated last October to Apple TV 3.0. The update added a redesigned main menu that aimed to make navigating content simpler and faster. It also allowed useres to watch iTunes Extras and iTunes LP content in full screen on their TV.

However, the software update failed to boost sales for the device, and Apple executives maintained their position that the Apple TV is simply a "hobby" for the Cupertino, Calif., company. In February, Chief Operating Officer Tim Cook said the set top box market does not compare with the other categories in which Apple competes, particularly media players, smartphones and computers.

Engadget's rumors would suggest that Apple would continue to sell the product as a set top box, while Google TV will be integrated with some HDTVs starting this fall. But analyst Gene Munster with Piper Jaffray has long believed that Apple could release its own connected HDTV, with Apple TV functionality built in to the device, in the next 2 to 4 years.

DateTime Range Helper In Rails View

There's some secret that you should know before you make time scaling in ruby on rails specially to the view. I have little smile when seeing helper from a developer that make time helper like in twitter or facebook, example a moment ago, or 3 minutes ago, or 1 hour ago. Why you hurt your brain if Rails already supports it. I think that he doesnt know the secret, now let me tell you the secret:

distance_of_time_in_words_to_now
Reports the approximate distance in time between from Time to time now. Set include_seconds to true if you want more detailed approximations when distance less than 1 min.  example :

<%=  distance_of_time_in_words_to_now(from_time, include_seconds =  false) %> 

distance_of_time_in_words
This is the same like above, but you can get range of time from 2 dateTimes, example :
<%=  distance_of_time_in_words_to_now(from_time, to_time = 0, include_seconds = false, options = {}) %>

below is table list from date range in many conditions:
0  - 29 secs # => less than a minute
30 secs to 1 min, 29 secs # => 1 minute
1 min, 30 secs to; 44 mins, 29 secs # => [2..44] minutes
44 mins, 30 secs to 89 mins, 29 secs # => about 1 hour
89 mins, 29 secs to 23 hrs, 59 mins, 29 secs # => about [2..24] hours
23 hrs, 59 mins, 29 secs to 47 hrs, 59 mins, 29 secs # => 1 day
47 hrs, 59 mins, 29 secs to 29 days, 23 hrs, 59 mins, 29 secs # => [2..29] days
29 days, 23 hrs, 59 mins, 30 secs to 59 days, 23 hrs, 59 mins, 29 secs # => about 1 month
59 days, 23 hrs, 59 mins, 30 secs to 1 yr minus 1 sec # => [2..12] months
1 yr to 1 yr, 3 months # => about 1 year
1 yr, 3 months to 1 yr, 9 months # => over 1 year
1 yr, 9 months to 2 yr minus 1 sec # => almost 2 years
2 yrs to max time or date # => (same rules as 1 yr)

 
powered by Blogger