Friday, August 24, 2012

Tuesday, March 6, 2012

Automate the process of running the test (watchr gem used with rails and rspec)

I today tried watchr gem while writing my unit test in rails application.It automate the process of running unit test. Watchr automatically run the test for the files which are change. That means if I changed Employee model then it will automaticall run employee_spec.rb . I found this gem very useful as save lot of time for manually run the test.

Installation watchr
Step 1.) Installing the gem
          gem install watchr
If you are using it with rails better bundle install the gem after adding the following code in gemfile

group :development, :test do
  gem 'rspec-rails'
  gem 'watchr'
end


Step 2.) Create .watchr file in root directory and add the following code:

def run_spec(file)
  unless File.exist?(file)
    puts "#{file} does not exist"
    return
  end
  puts "Running #{file}"
  system "bundle exec rspec #{file}"
  puts
end

watch("spec/.*/*_spec.rb") do |match|
  run_spec match[0]
end

watch("app/(.*/.*).rb") do |match|
  run_spec %{spec/#{match[1]}_spec.rb}
end


Step 3.) run the following command:
watchr .watchr


Now you can make change in your code and then automatically respective spec will run.

References :
https://github.com/mynyml/watchr
http://www.rubyinside.com/how-to-rails-3-and-rspec-2-4336.html


Tuesday, February 28, 2012

Which mobile platform is the best Native or Web app ?


Mobilize your website: Native App or Mobile Web?

There is mobile buzz going on, every one want that there website should have access to smart phones. It was till last year that only Social/e-commerce sites have mobilized but now because of phenomenon growth of smart mobiles and tablets there is also good growth in enterprise applications. Each sector whether it is Education, Health, Social etc every one is trying to be mobilized.
In mobile world things are not simple as web development as there are lot of different devices  available. There is no standard in these devices and that's also changing at very fast rate. I will give you an example I am working on mobilizing BMC IT Service management. When we started we did a survey about which mobile device is mostly used by our Clients. The number of Blackberry users at that time were huge. So we started development concentrating on Blackberry but then we realized that iphone number has grown at very fast rate and our customers want the product for iphone also. It was good that we designed our API’s and code in good way that it does not take much time to release the same product for iphone also. So coming back to point the mobile world is changing at very fast rate, we can’t decide which platform will lead the future but choosing the right framework and designing good API will always help you.
I got frequently get mail and call by many companies and people asking which framework is good for creating Mobile application or asking which is better Native application or Web application. So just thought to consolidate all the ideas.

To start with we can create  mobile application in three type way:
Native Apps:
These are platform specific application which is coded in platform specific language like Objective C for iphone/ipad, Java for Andorid etc.
Mobile games are develop using this application.

Advantages:
  • This application are reliable, performance is good and very powerful.
  • Can use Device Cabiblity like GPS, phone book, camera etc
  • You can have push Notifications 

Disadvantage:
  • Take lot of time for Development
  • Creating and maintain cost is very high as we have to code for each platform.
  • Finding language specific resource for this language is big task. As we need dedicate resources which are expert in these languages.
  • Have to submit to Appstore which is a painful process.

Mobile Web application:
These are the simple web application which can be access from each web enable device.
Advantage:
  •   Don’t need for Appstore submission. This is the most painful and time consuming process.
  •  Cross platform- work on all HTML5 devices like iphone, Android and Blackberry
  •  Easy to create and maintain.
Disadvantage:
  •           Not work well for touch phones( Can use some CSS framework for touch effect)
  •           This application are not very fast and not reliable
  •           No Offline Capability
  •           Can’t use Device Capbilities and push notifications

Hybrid Applcations
These are application which are created with some HTML5 based framework like Rhomobie, phonegap, titanium. These application can access device capability with there API and easy to code.
Advantage
  • Development is very fast,
  • Cross platform
  • Can use device capability and push notifications
Disadvantage:
  • If you need any specific feature you have to wait until these framework support that feature.
  • Choosing between these framework is difficult task. Each has its advantage and disadvantages.

So choosing in between depends on your requirements:

Sites like standard e-commerce sites, Social Networking site speed and experience can make a huge difference in the effectiveness of a mobile commerce website or native application. Sites that are slow to load — even by just a second or two — can often lead to users forgoing the transaction altogether. For this type of application I think Native application is best solution.

Sites like Enterprise application, Events, meetups etc were ease and time of development is important  there Hybrid application are best solutions. You can also use device capability, offline capabilities with them. 

If your application is used to check certain information and don’t want any offline capabilities/Device capabilities than Mobile Web application is best solutions.

And most important, design your API in good way so that they can be reused easily.

To know about different framework available follow this link

Also i have presentation in RubyConfIndia 2012 about "Which Mobile platform should i choose?"

Monday, January 9, 2012

Proc vs lamda in ruby

The are two major difference between procs and lambda 

1.) A proc can break the parent method, return values from it, and raise exceptions, while such statements in lambda will only affect the lambda object. 


def foo
  f = Proc.new { return "return from foo from inside proc" }
  f.call # control leaves foo here
  return "return from foo"
end

def bar
  f = lambda { return "return from lambda" }
  f.call # control does not leave bar here
  return "return from bar"
end

puts foo # prints "return from foo from inside proc"
puts bar # prints "return from bar"

2.) The other difference is unlike Procs, lambdas check the number of arguments passed.

def some_method(code)
  one, two = 1, 2
  code.call(one, two)
end

some_method(Proc.new{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

some_method(lambda{|first, second, third| puts "First argument: #{first} and Second argument #{second} and Third argument #{c. third}"})

# => First argument: 1 and  and Second argument 2 and Third argument NilClass
# *.rb:8: ArgumentError: wrong number of arguments (2 for 3) (ArgumentError)

We see with the Proc example, extra variables are set to nil. However with lambdas, Ruby throws an error instead.

Sunday, January 8, 2012

rhomobile tutorial and Example

If you are new to Rhomobile and don't know how to start with Rhomobile products. Then may be this blog will helpful to you. I have consolidate all the tutorials and Examples.

Book

Docs

Webinar

Presentations

Examples


I will keep updating this with new example and sources to learn Rhomobile products

Rhomobile Ajax Calls using JQuery Mobile

Note: This will only work on IPhone,Android and Blackberry(version 6 and above) 

There is common scenario to use Ajax with Rhodes but I was not able to find good source to use them so thought of blogging it. I will be using Jquery Mobile framework which is by default with Rhodes.

In this example I will load some text inside a div on clicking of a button.

Step 1.) Create a div and button on a page
<input type= "button" id="some-button"/ name="button" value="Load Value By Ajax">
      <div id= "some-div">
      </div>


Step 2.) Create a Javascript 

Step 3.) Create a action ajax_method in controller
def ajax_method
    @some_value = "Its all about ruby ---" +@params['some_variable']
    render :action => :ajax_method, :layout => false, :use_layout_on_ajax => false
  end

Step 4.) Create a ajax_method.erb file
<i><b><%= @some_value %></b></i>

It is just a very basic example you can do many more things like error handling, adding loading image etc.



Tuesday, December 27, 2011

Refreshing the column in rails


It may be possible that your database is shared with multiple applications and you data are frequently changing. You can manually refresh the object by:

stock = Stock.find_all
loop do
puts “price = #{price}”
sleep 60
stock.reload
end


Monday, December 19, 2011

Rails Observers vs Callbacks


Rails Callback

Callbacks are methods that get called at certain moments of an object’s life cycle. That means that it can be called when an object is created, saved, updated, deleted, validated, or loaded from the database.

A callback is more short lived. And you pass it into a function to be called once. 


Rails Observers

Observer is similer to Callback but it is used when method is not directly related to object lifecycle. The other difference is an observer lives longer and it can be attached/detached at any time. There can be many observers for the same thing and they can have different lifetimes. 
The best example of Observer is that it could be “send registration confirmation emails” As we can argued that a User model should not include code to send registration confirmation emails so we will create observer for this.



Thursday, November 24, 2011

Rhodes Iphone Build using Xcode


In this post we will create Rhodes build from Xcode. Though we can do this by rake run:iphone for development and rake run:iphone:production for Production but for better understanding and advance configuration we can do the same with Xcode. 

To start quickly,  these are the prerequisite:
  •        Valid Provision Profile should be installed.
  •        Valid Certification should be installed.

For getting these Certification login to Apple Development Center and navigate to iOS Provisioning Portal.

Now to get started follow these steps:
  •    Go to your project folder from Terminal and type:          

             $rake switch_app

The switch_app command changes the rhobuild.yml in the Rhodes source code folder to point to your application, as in the following example for a Rhodes application named Store in the user’s home folder:

env:   
    app: /Users/Name_Of_User/Application_name
  
  • Now run the following command to tell Rhodes to set up the Xcode environment for your Rhodes application:

          $ rake build:iphone:setup_xcode_project

  •    Open rrhorunner.xcodeproj project. This will open your application in Xcode. You can find this project in Gems folder of ruby -> Rhodes-> Platform-> iphone. After opening the project we can see rhorunner project is open in Xcode.


  • To run the application select rhorunner project and then select where you want to run the application. If you have connect iOS device it will appear on list for example in given image I have connected my iphone "Abhishek Nalwaya's iPhone"





If we select "Abhishek Nalwaya's iPhone" and click on Run then it will automatically create the build and install the application on the device. To run in the simulator you can select from the list. 

Debugging Notes: 
  • Make sure you have register the device to appstore for testing.
  • Make sure you have selected correct Code Signing 


  • If you want to restore the XCode use following command:

              $rake build:iphone:restore_xcode_project


If you face any issue feel free to comment on this post.


Monday, October 10, 2011

Motorola Solutions acquires Rhomobile


It is officially announced yesterday that Motorola Solutions has acquires Rhomobile. So this ruby based Mobile Framework is now part of  Motorola Solution. Few week back it was announced that HTML5 based Mobile Framework Phonegap is acquire by Adobe.  So is it Mobile/HTML5 buzz?
Motorola  announced the availability of Motorola RhoElements, a state-of-the-art web-based application framework. It is designed to allow businesses to quickly and cost-effectively develop and deploy web-based applications on existing Motorola Windows Embedded Handheld (formerly known as Windows Mobile) and Windows Embedded Compact (Win-CE) mobile computers as well as Motorola’s recently announced ET1 Android-based enterprise tablet.

These are the key notes of acquisition:
  • All Rhomobile products will continue to be sold and supported globally.  
  • Rhodes will continue to be available open source under the MIT License.
  • They are committed to supporting the Rhomobile community and continuing the open source heritage of Rhodes
  • They also announced their updated Windows Mobile focused mobile browser  now called RhoElements. 
  • Motorola Solutions will provide the scale, resources, industry knowledge, and broader base of partners and channels to accelerate universal adoption of Rho technology



Reference :
http://mediacenter.motorolasolutions.com/Press-Releases/Motorola-Solutions-Offers-Industry-s-First-Framework-for-Developing-HTML5-Applications-on-Windows-Embedded-Handheld-and-Windows-CE-Devices-3741.aspx

http://www.marketwatch.com/story/motorola-solutions-offers-industrys-first-framework-for-developing-html5-applications-on-windows-embedded-handheldtm-and-windows-cetm-devices-2011-10-10

http://techcrunch.com/2011/10/10/motorola-launches-rhoelements-an-html5-framework-for-building-mobile-apps-for-enterprise/

Thursday, September 22, 2011

git branching

There is very nice example given by Satish Talim on git Branch on Google +. Though it is basic but I like the example, that's why sharing the link:


Satish Talim - Google+ - The Free, Online Git / GitHub 101 Course ( Link to Day 7 -…:

'via Blog this'

Thursday, September 1, 2011

Rhomobile Ipad Example- You Tube Client

We will create a Rhomobile ipad application which will search youtube videos and will playback this videos. It is just an example and our purpose is to explore Rhomobile AsyncHttp methods. We will connect to You tube search API. 


Step 1.) Create Rhodes application :
              rhogen app youtube_client
   
Step 2.)  Go to application directery:
              cd youtube_client/

Step 3.)  Create a controller Youtube

Step 4.) Create action search and search_result in youtube_controller.rb



   def search

   end

    def search_result
        you_tube_url = "http://gdata.youtube.com/feeds/api/videos?q=" + @params['name'] + "&max-results=5&v=2&alt=jsonc"
        @youtubes= Rho::AsyncHttp.get(
                                       :url => you_tube_url
                                       )["body"]["data"]["items"]
    end

 We are using AsyncHttp to call You Tube search API. And @params['name'] contain the search term.

5.) Create search.erb 


<div data-role="page">


  <div data-role="header" data-position="inline">
    <h1>Search You tube</h1>
    
  </div>


  <div data-role="content">
    <form method="POST" action="<%= url_for :action => :search_result %>">    
          <div data-role="fieldcontain">
            <label for="name" class="fieldLabel">Name</label>
            <input type="text" id="youtube[name]" name="name" />
          </div>
      
      <input type="submit" value="Update"/>
    </form>
  </div>


</div>




6.) Create search_result.erb and add following code:


<div data-role="page" data-add-back-btn="false">


  <div data-role="header" data-position="inline">
    <h1>Search result</h1>
  </div>


  <div data-role="content">
    <ul data-role="listview">
      
         <% @youtubes.each do |youtube| %>
        <li>
      <center>
            <span class="title">
<%= youtube["title"] %></span><br>
<iframe width="400" height="400" src="http://www.youtube.com/embed/<%= youtube["id"]%>" frameborder="0" allowfullscreen></iframe></center>
<span class="disclosure_indicator"></span>
      
        </li>
    
    <% end %>      
    </ul>
  </div>


</div>







7.) Link the search.erb to home page(by default it is index.erb in app folder.

8.) If you creating it for ipad add following line in build.yml under iphone.
      emulatortarget: ipad
If you creating this app for iphone or Android you can skip this step.

You can Download this code from : https://github.com/nalwayaabhishek/YouTubeClient 

Tuesday, August 16, 2011

Connect Rails and Redis

These days Redis is getting very popular because of its document style storage and high performance. It is a persistent in-memory key-value store written in C by Salvatore Sanfilippo. Redis is an open source, advanced key-value store. It is often referred to as a data structure server since keys can contain strings, hashes, lists, sets and sorted sets.

When to use Redis :
  • You want to access the data very fast.
  • Your data set is not big and it can fit in available RAM
  • And your data is not very critical if it loose due to any failure 

Install redis:
Download and install from http://redis.io/download


Start Redis
Go to terminal and type :
./redis-server
By default it will run on port 6379

Connecting Redis with Rails 
Once Redis is installed and running follow these steps:
1.) Open gemfile
gem 'redis', '2.1.1'
2.) Then go to your application directory from terminal and execute:
bundle install
3.)Go to following directory /config/initializers/ and create a file redis.rb
4.) Write the following code in redis.rb
$redis = Redis.new(:host => 'localhost', :port => 6379)
By default redis run on 6379, if you are running on different port change this port attribute.

All configuration is completed and now you can use $redis global variable from your rails application.
Checking the connection :
Go to rails console and type following command
 >$redis
=> Redis client v2.1.1 connected to redis://localhost:6379/0 (Redis v2.2.2)

Some Redis Examples
> $redis.set("website","itsallaboutruby")
=>"OK"
>$redis.get("website")
=>"itsallaboutruby"
>$redis.set("count",1)
=> "OK"
>$redis.incr("count")
=>2

Monday, August 1, 2011

Rhomobile Book

Finally My Book on Rhomobile has been publish with pactpub.

Now Its time to say Thanks.


I would like to express my gratitude to my family and friends especially Akshat Paul, Manu Singhal, and Anuj Bhargava who saw me through this book, who provided support, talked things over, read, wrote, offered comments, without which conceiving this book wouldn't have been possible.

Also, I would like to thank Sarah, Neha, Kartikey, Shubhanjan, and the PacktPub team who allowed me to quote their remarks and assisted in the editing, proofreading, and design. Writing a book was not my cup of tea but they made this complicated journey effortless.


Also I want to say big thanks to Reviewers:
Brian Moore :
Brian Moore is a Senior Engineer at Rhomobile, father of two, and quintessential hacker.
Brian began coding at the age of 12. His early love for everything technological led to a job with Apple shortly after high school. Since that time Brian has worked at a series of start-ups and tech companies taking on interesting technical challenges. Brian has become the
technical face of Rhomobile as he leads the Rhodes community in the latest Rhomobile innovation during the Friday webinars. When not guiding the next generation of Rhodes developers or hacking on a new debugger, Brian can be found climbing a hill in a remote Southern California desert in his baja bug.


Deepak Vora is a consultant and a principal member of the NuBean.com Software Company. Deepak is a Sun Certified Java Programmer and Web Component Developer, and has worked in the fields of XML and Java programming and J2EE for over five years. Deepak is the co-author of the Apress book Pro XML Development with Java Technology and was the technical reviewer for the O'Reilly book WebLogic: The Definitive Guide. Deepak was also the technical reviewer for the Course Technology PTR book Ruby Programming for the Absolute Beginner, and the technical editor for the Manning Publications book Prototype and Scriptaculous in Action. Deepak is also the author of the Packt Publishing book JDBC 4.0 and Oracle JDeveloper for J2EE Development, Processing XML documents with Oracle JDeveloper 11g, and EJB 3.0 Database Persistence with Oracle Fusion Middleware 11g.

Other contributors:


Acquisition Editor
  • Sarah Cullington
Development Editor
  • Neha Mallik
Technical Editors
  • Ajay Shanker
  • Mohd. Sahil
Project Coordinator
  • Shubhanjan Chatterjee
Proofreader
  • Linda Morris
Indexer
  • Geetanjali Sawant
Graphics
  • Melwyn D'Sa
Production Coordinator
  • Melwyn D'sa
  • Cover Work
  • Melwyn D'sa


This is the link to buy the book :Rhomobile Book





Sunday, July 3, 2011

$(‘#form_id’).submit() does not work with Rhomobile+ jQtouch

If you are using Rhomobile and jQtouch together you may find that  $(‘#form_id’).submit();  will not work.  Use jQT.submitForm(‘.current form.yourFormClass’); instead of submit.

Thursday, May 5, 2011

Rhomobile IDE


 You may be wondering which IDE should I use for Rhomobile Development?

I’m writing this mainly as a guide for people just getting started with Rhomobile, so don’t freak out if you don’t see any editor. These are just some that I recommend you try if you’re first starting. 
All of these are free. 

You can use any IDE of your choice which support ruby.
One of the Best IDE for ruby are:
  • TextMate
  • NetBeans
  • Eclipse
  • Rhohub Online Editor
  • RhoStudio

I love to use Textmate on my Mac. For Windows you can use RhoStudio.

RhoStudio Beta,the IDE for Rhomobile technology is launched recently. It is a local Eclipse IDE that performs app generation, editing, and build of all Rhodes projects. 

So Start coding..enjoy...

Thursday, April 14, 2011

Review:Rhomobile vs Appcelerator/titanium vs PhoneGap Which one is Best?



What all Products are available for Mobile Application Development?
To know about Native application,Web application and Hybrid application follow this link

There are plenty of players available for Mobile Development.
The major frameworks in market are
·       Appcelerator Titanium
·       DroidDraw
·       PhoneGap
·       Rhomobile
·       Application Markup Language (AML) etc.

Each of these frameworks has its own advantage and disadvantage. The choice of frameworks depends on project’s requirements.
Each platform for mobile applications also has a development environment which provides tools to allow a developer to code, test and deploy applications into the target platform environment. There are also Legacy Providers which are platform specific. 

In following table we have shown comparison of Rhodes with Legacy Provider and other frameworks.


Rhodes
Legacy Providers
Other Framework
Support all Smart Phone
Yes
No
No
Native UI
Yes
Yes
Yes
App Language
Standard
Proprietary
Standard
Model View Controller
Yes
No
No
Barcode/Signature Capture
Yes
Yes
No
HTML5
Yes
No
Yes
Support all OS
Yes
No
No
MetaData
Yes
No
No
Sync
Yes
No
No
Native Push API
Yes
No
No
Hosting Facility
Yes
No
No

  (Source : www.rhomobile.com )

Why Rhomobile is different from other products in market?

·       Model View Controller
Most of the other framework available in market are based on HTML and JavaScript . Hence other frameworks force us to put all business logic into the view and JavaScript. However, as Rhodes is ruby based framework and its structure is similar to popular framework Rails it also support Model View Controller, so code written with Rhodes is more structured and easy to understand.

·       Cross Platform Support for All Devices
Rhodes supports far more device operating systems than any other framework: iPhone, Android, Windows Mobile, BlackBerry and Symbian. The best thing is you have single code base from which you can build application for different smart phone. It does not work legacy way that we have to write seperate code for different types of phones.

·       Offline Capabilities using Rhosync
Rhomobile supports local synchronization of data. Older sync servers don’t support modern smartphones such as iPhone and Android. Most iPhone developers that need sync just end up writing their own synchronization code or process. As we can synchronize the data using Rhosync it provide offline Capabilities. We can work even if you are offline.

·       Object Relational Manager
Rhodes provides inbuilt Object Relational Manager called Rhom. It is similar to Active Record in Rails but with basic functionality only. It helps us to write queries without thinking about which database is being used by phone

·       Rapid Development
One of the interesting features of Rhodes is that it imposes some fairly serious constraints on how you structure your applications which help us for Rapid development. Rhomobile products are properly structured and well organized which enforce  us to do rapid development. Modern web developers have found Rhodes to be very comfortable, familiar and massively productive.

·       Scalable Sync Server
The Sync Server uses NoSql Database which makes it scalable. In addition, RhoSync has several compelling advantages over other sync servers yet built. Specifically it is the only sync server that has a built-in “no SQL”  Redis key value store, making it more scalable than other sync servers who offers internal relational database servers for caching. RhoSync also performs its push-based sync using the native smart phone push SDKs, which no other sync server does.

·       Liberal use of code generation
 Rhodes/RhoSync can write lot of code for you. For example, when you need a class to represent a table in your database, you don't have to write most of the methods. Rhodes even offers an application generator that creates an initial app based on the structure of your models or business objects in your app. It’s very similar to the scaffolding offered by most modern web frameworks with basic “list/create/read/update/delete objects” functionality. For each basic CRUD action, views in HTML are also offered. App developers spend most of their time just modifying views as they see it. No other framework provides an app generator, nor does any SDK. Rhodes looks at the table's definition and creates most of the class. You'll find that you're writing only a fraction of code compare to other frameworks.

·       Metadata
Every enterprise application that is used to run a company’s core business has a different schema for its business objects. For example, every application has varying and customized structure that changes with time. It is not possible to install the client application again and again for a small change. Metadata framework provides a way to handle the view from Rhosync server. It also provides validation and custom template.

·       Hosted Development and Build
Rhomobile also provides a hosted management and Build through Rhohub. We can deploy Rhosync app and build our Rhodes code for different phones with it. No other products in market offer such functionality or feature as of now.
  
PhoneGap
PhoneGap is an HTML5 app platform that allows you to write native applications with web technologies and get access to Native Capabities of phone with ease. PhoneGap uses standards-based web technologies to bridge web applications and mobile devices.

Strengths :

  • Can use HTML5 and CSS3
  • Deploy your app to Multiple Platforms (Symbian and Bada is also supported)
  • Access Native Features
  • Use JavaScript to write your code
  • Licence under Apache Software Foundation
  • Very well documented
  • PhongGap APIs are more generic and can be used on different platforms such as iPhone, Android, Blackberry, Symbian, etc 
Weakness:
  • No MVC
  • No ORM

Appcelerator Titanium
Appcelerator Titanium is an open source mobile application development tool for iPhone and Android. We can also create Desktop application with titanium. It allows you to code apps with HTML, CSS and JavaScript. Titanium primarily uses Javascript and JSON code to write your Native application. It supports Ruby, Python, and PHP scripts for broad developer coverage. If you are creating any social media mobile app then it is better option as Facebook, Yahoo etc API is available with titanium.
Documentation is available here: http://developer.appcelerator.com/documentation

Strengths:

  • Compiles to truly native application code, not HTML5
  • Very large library of APIs for all kinds of activities and data access
  • Uses Javascript/JSON for primary language
Titanium appears to be more feature rich than PhoneGap by bridging more mobile phone functions to javascript. 

Weakness
  • Only support iphone and Android
  • No MVC and ORM
Rhodes and Phonegap does NOT compile your html, css or javascript code into "native bits". When the application runs, these resources use  UIWebView control and run there. From architectural standpoint, these the frameworks are very similar. 

Also i have presentation in RubyConfIndia 2012 about "Which Mobile platform should i choose?"