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

Automatic page refresh using Ajax

Ajax On Rails 1 Comment »

Recently, I had come through a requirement where in I had a form which on submitting runs a sql query to get the data from the database based on the submitted form values.Here the primary requirement was to reload the form after every one minute with the same form data to be passed recursively until the user does not modify it.

So whille the solving this issue, I had come through the following approaches for implementing the Auto Refresh while maintaining the form data:

Approach 1:

The HTML Based META Refresh

I feel that this approach is the best when refreshing a static webpage.

It involves the following syntax

<meta http-equiv=”refresh” content=”60;url=http://localhost:3000/admin?param1=params1&params2=param2″>

Here the content = 60 tell the web browser to refresh the page after every 60 seconds the url maps the link to refreshed.

Note: Now when coming to RoR, The url will just represent the action name somewhat like

content=”60;url=/action?param1=params1&params2=param2″

The caveat in this method that I found for my requirement was I had form with many fieldsets and form helpers so the string that i passed to url seemed to be looking very ugly.So I decided to go for the ajax based page refresh whcih looks something cooler then this.

Approach 2 :(Recommended)

The Ajax Periodical Updater

I feel this is the coolest way and the one line code to achieve thsi functionality is use the ajax periodical updater. It comes as a Ajax based Rails helper whisch is formatted as follows

<%=periodically_call_remote(:update => “myDiv”,:frequency => 60, :url => { :action => “action_name”, :params=>params }) %>

Here I am updating the div with id as “myDiv” and relading the same at a time interval of 60 secs.I had to place this div at the immediate start of the HTML body tag and before the immediate end of the body tag as my requirement was a full page reload.

The periodically_call_remote is rendered in the HTML Template as follows

<script type=”text/javascript”>
//<![CDATA[
new PeriodicalExecuter(function() {new Ajax.Updater(’myDiv’, ‘/action_name?params1=params1& params2=params2, {asynchronous:true,evalScripts:true})}, 20)
//]]>
</script>

So wrapping up, I would like to say that the moral of this post I would like to ajax can be used to refresh the page, there by breaking the bounds of the so called REST architecture.

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

Test Driven Development in RoR

RoR Testing No Comments »

Here’s TDD- new code developement technology in this rails jungle that make the business processes clearer for developers …..
Here we use the test to drive the code…..not the code to make the tests crazy..
Just starting of with a few points for u here which will track u down on the base of TDD

Test Driven Design
aka “Test First”
Drives design desisions through testing.
Ensures things are testable.•
Provides a fast and tight feedback loop.
Attacks the problem at the specification level.
Doesn’t wait until the last minute to see if things work.

TDD Mantra On The Go
•Red - produce failing testcase
•Failures should make you happy!
•Go Green - implement and pass test
•Refactor - clean up - made safer by previous two steps
•Repeat until done

Lets Think Practically:
Im using a simple bank account example for the TDD clearence in u r minds

class AccountTest < Test::Unit::TestCase
def test_new_account_should_have_zero_balance
account = Account.new
assert_equal 0, account.balance
end
end
Its time to run the test:
E 1) Error: test_new_account_should_have_zero_balance:
NameError: uninitialized constant Account ./test/unit/account_test.rb:6:in `test_new_account_should_have_zero_balance’
1 tests, 0 assertions, 0 failures, 1 errors

Oppsss..got a name error… yahh..i got it.. i think i have to play with migrations now… since our failing test is crying taking the name error
class CreateAccount < ActiveRecord::Migration
def self.up create_table “accounts”, :force => true do |t|
t.column :balance, :integer, :default => 0
end
end
end

We will leave the model as it is for the timebeing….lets not play with it…
class Account < ActiveRecord::Base
end

Then we run the test again to make is pass…lets see…
Started . Finished in 0.055268 seconds.
1 tests, 1 assertions, 0 failures, 0 errors
Hurray…that looks pretty good…

Lets depoesit some money into the account…we write the test first..
class DepositTest < Test::Unit::TestCase
def test_should_update_balance_when_making_deposit
account = Account.new account.deposit(10)
assert_equal 10, account.balance
end
run the test…
E 1) Error: test_should_update_balance_when_making_deposit(DepositTest): NoMethodError: undefined method `deposit’ for #
./test/unit/deposit_test.rb:8:in`test_should_update_balance_when_making_deposit’
2 tests, 1 assertions, 0 failures, 1 errors

Oh..Yeahh..It failed again….

The model comes into the picture now:
class Account < ActiveRecord::Base
def deposit(amount)
end
end
Just a little change …and we run the test back again..
1) Failure: test_should_update_balance_when_making_deposit:
<10> expected but was
<0>.
2 tests, 2 assertions, 1 failures, 0 errors
Ohhh…My assertion failed….I think I need to add more in the model…
class Account < ActiveRecord::Base
def deposit(amount)
self.balance += amount #adding the amount to the existing balance
end
end
Finally run the test again….It should pass everything…
Started..Finished in 0.242602 seconds.
2 tests, 2 assertions, 0 failures, 0 errors
Yup…Im on TDD…Its really that simple…!

Moral of the story:

  • With TDD u can can have a total control over your code and application working..
  • We really dont need any testers banging their head doing out some testing on a full proof code developed through TDD technique…
  • Enhances better code refactoring methods and also assures better code coverage for the tests…
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

Unit testing in Rails: How To???

RoR Testing 1 Comment »

Steps in unit testing:

Unit test are mainly used to test the models in Rails.
Generally, there is one test for each model.
Unit testing involves testing the databases and the business rules in the model.
Default test Stub are created when you run script/generate model

Division of a unit test:
· GENERATION OF A TEST DATABASE
· WRITING THE UNIT TEST CASES INCLUDING ASSERTIONS.
· LOADING THE .YML FILE WITH DEFAULT VALUES
· RUNNING THE TEST CASE.

Writing the unit test case involves the following steps:
The first steps in the unit test case involves creation of the test database for the testing purpose which can be generated from the following command:
rake clone_structure_to_test or rake db:test:clone_structure
All the test cases for the models are written under the /test/unit directory.
The test class is the is the subclass of the Test::Unit::TestCase base class which tells the rails to generate the tests based on the Test::Unit framework.
Assertions can be used to test the necessary checkpoints within the test case.
Assertions are triggers which validate or test the current state of a webapp during the runtime.
After the preparation of the test case, we load the test database with some default data using fixtures.
Fixtures are available under the test/fixtures directory under the webapp.
We edit the .yml file to match the records in the test database and load the records with some default data.
To run the test we use the following command:
rubytest/unit/.rb

Checking The Code Coverage Of The Test:Using RCOV

Rcov takes the .rb files as the input and checks the code coverage of the test on the model file and generates the code coverage statistics as a html files and stores it in the folder named coverage in your webapp.
Optimizations then need to done on the .rb file until it shows a code coverage of almost 95-100%

Assertions:
The following is the list of assertions that can be used while writing the unit test cases:
Note:The [msg] is an optional string message you can specify to make your test failure messages clearer. It’s not required.
*assert* ( boolean, [msg] ) … ensures the object/expression is true
*assert_equal* ( obj1, obj2, [msg] ) … ensures obj1 obj2 is true @*assert_not_equal* ( obj1, obj2, [msg] )@ … ensures obj1 obj2 is false
*assert_same* ( obj1, obj2, [msg] ) … ensures obj1.equal?(obj2) is true
*assert_not_same* ( obj1, obj2, [msg] ) … ensures obj1.equal?(obj2) is false
*assert_nil* ( obj, [msg] ) … ensures obj.nil? is true
*assert_not_nil* ( obj, [msg] ) … ensures obj.nil? is false
*assert_match* ( regexp, string, [msg] ) … ensures a string matches the regular expression
*assert_no_match* ( regexp, string, [msg] ) … ensures a string doesn’t matches the regular expression
*assert_in_delta* ( expecting, actual, delta, [msg] ) … ensures the numbers expecting and actual are within delta of each other
*assert_throws* ( symbol, [msg] ){ block } … ensures a block throws the symbol
*assert_raises* ( exceptions ){ block } … ensures a block raises one of the comma-separated exceptions
*assert_nothing_raised* ( exceptions ){ block } … a block doesn’t raise one of the comma-separated exceptions
*assert_instance_of* ( class, obj, [msg] ) … ensures obj is the class type
*assert_kind_of* ( class, obj, [msg] ) … ensures obj is or descends from class
*assert_respond_to* ( obj, symbol, [msg] ) … ensures obj has a method called symbol
*assert_operator* ( obj1, operator, obj2, [msg] ) … ensures obj1.operator(obj2) is true
*assert_send* ( array, [msg] ) … ensures that executing the method listed in array[ 1 ] on the object in array[ 0 ] with the parameters of array[ 2 and up ] is true. This one is weird eh?
*flunk* ( [msg] ) … ensures the failure of the test

Here is a Demo example:
Example :Person Test: /test/unit/person_test.rb
require File.dirname(__FILE__) + ‘/../test_helper’
fixtures :person
class PersonTest < Test::Unit::TestCase
def setup
@people = Person.new
end
def test_something
#Write your test cases along with the necessary assertions here.
assert true, “Test implementation missing”
end
end

#example of the password test case.
def test_passwords
jimmy = Person.new
jimmy.first_name = ‘Jimmy’
jimmy.last_name = ‘McJimmy’
jimmy.password = ‘h1st0r3ct@my’
#The assertion lineup
assert !jimmy.password.empty?
assert jimmy.password.length > 5
assert_match /(0-9)/, jimmy.password
assert_not_equal ‘password’, jimmy.password.downcase
end

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

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