Saturday, July 15, 2006

Generate RSS Feed


Neha Gupta
has submitted this Ruby code snippet:
xml.rss(:class => "Recipe", :version => "x.x", :xmlns
=> "www.codewalla.com") do
xml.channel do
@Recipes = Recipe.find_all
xml.title("List of Recipes -- Total ", Recipe.count,
" recipes")
xml.link
xml.description
xml.RecipesAuthor("CodeWalla")
@Recipes.each do |item|
xml.item do
xml.Title(item.title)
xml.link
xml.author("CodeWalla")
xml.desciption(item.description)
xml.date(item.date)
xml.category(item.category.name)
end
end
end
end
The above code is made to generate a rss feed of a particular table from a database. Here, Recipe is a table name and item is the variable in m used to store one recipe temporarily, to display its contents. This code needs to be stored in .rxml file.
Eg: D:/Copy of rails/cookbook/app/views/actor/index.rxml

It can be invoked by:
http://localhost:3000/actor/index.rxml

The output of the code is:
<rss xmlns="www.codewalla.com" version="x.x" class="Recipe">
<channel>
<title>List of Recipes -- Total 4 recipes</title>
<link/>
<description/>
<RecipesAuthor>CodeWalla</RecipesAuthor>
<item>
<Title>codewal;l</Title>
<link/>
<author>CodeWalla</author>
<desciption></desciption>
<date></date>
<category>Dessert</category>
</item>
<item>
<Title>bbbbbbbbbbbbbb</Title>
<link/>
<author>CodeWalla</author>
<desciption>bbbbbbbbbbbbbb</desciption>
<date>2006-05-04</date>
<category>Starters</category>
</item>
<item>
<Title>dsfhsjdflk</Title>
<link/>
<author>CodeWalla</author>
<desciption>;kkb;k</desciption>
<date>2006-05-04</date>
<category>Starters</category>
</item>
<item>
<Title>Ice Tea</Title>
<link/>
<author>CodeWalla</author>
<desciption>Good !!!</desciption>
<date>2006-05-04</date>
<category>Dessert</category>
</item>
</channel>
</rss>
Kindly comment on this code.
Technorati Tags:
Blogs linking to this article

Friday, July 14, 2006

July 2006 PuneRuby meet

The PuneRuby meet is fixed for this Sunday, 16th July 2006 at 17.00 hrs. The venue, as usual, is SICSR, Model Colony, Pune. The speakers are:

a. Shashank Date - President of Reevik Inc, Kansas, USA. Has an overall experience of 19 years in IT. A known name in the Ruby world, one of the programmers of the Ruby's one-click installer, and is one of the early adopters of Rails.

b. Dibya Prakash

Anyone else interested in speaking kindly let me know asap, the topic and your background.
Technorati Tags:
Blogs linking to this article

Thursday, July 13, 2006

Validation in Rails

Let's try our hand at some validation. No participant should be allowed in the database if it has an empty text field or an invalid URL for the blog_url. So, where do we put the validation? The model layer is the gatekeeper between the world of code and the database. Nothing to do with our application comes out of the database or gets stored back into the database that doesn't first go through the model.

This makes it an ideal place to put all validation; it doesn't matter whether the data comes from a form or from some programmatic manipulation in our application. If the model checks it before writing to the database, then the database will be protected from bad data.

Let's look at the source code of the model class (in app/models/participant.rb).
class Participant < ActiveRecord::Base
end
Not much to it, is there? All of the database mapping, creating, updating, searching, and so on is done in the parent class (ActiveRecord::Base, a part of Rails). Because of the joys of inheritance, our Participant class gets all of that functionality automatically.

Let's start by validating that the text fields all contain something before a row is written to the database. We do this by adding some code to the existing model, as follows:
class Participant < ActiveRecord::Base
validates_presence_of :name, :city, :blog_url
end
The validates_presence_of( ) method is a standard Rails validator. It checks that a given field, or set of fields, is present and its contents are not empty. The screen shot, shows what happens if we try to submit a new product with none of the fields filled in. It's pretty impressive: the fields with errors are highlighted, and the errors are summarized in a nice list at the top of the form. Not bad for one line of code. You might also have noticed that after editing the participant.rb file you didn't have to restart the application to test your changes. Rails notices that the files have been changed and reloads them into the application. This is a tremendous productivity boost when developing.

We also want to make sure that each partcipant has a unique blog_url. One more line in the Participant model will do this. The uniqueness validation will perform a simple check to ensure that no other row in the participants table has the same blog_url as the row we're about to save.
validates_uniqueness_of :blog_url

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

Adding a Missing Column

Let's say we decide that our participants table needs an additional column for storing the participant's blog URL. This means we'll need to add a column to the database table, and we'll need to make sure that the various maintenance pages are updated to add support for this new column. Let's alter the file db/create.sql, adding the blog_url column. Let's save this file as create2.sql as shown here:
drop table if exists participants;
create table participants (
id int not null auto_increment,
name varchar(100) not null,
city text not null,
blog_url varchar(200) not null,
primary key (id)
);
When I first created this file, I added a drop table command at the top of it. This now allows us to create a new (empty) schema instance with the command:
c:/rails/work/student>mysql student <db/create2.sql

Obviously, this approach only works if there isn't important data already in the database table (as dropping the table wipes out the data it contains). That's fine during development, but in production we'd need to be careful.

The schema has changed, so our scaffold code is now out-of-date. As we've made no changes to the code, it's safe to regenerate it. Notice that the generate script prompts us when it's about to overwrite a file. We type Y to indicate that it can overwrite all files. The command is:
c:/rails/work/student>ruby script/generate scaffold Participant Admin

You can now enter the new data and the screen should look like this.

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

Wednesday, July 12, 2006

Configuring the Application

Rails uses a flat file located in config/database.yml to store the information on how to connect to the database. This file should be edited to look like this:
# MySQL (default setup).  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
# gem install mysql
# On MacOS X:
# gem install mysql -- --include=/usr/local/lib
# On Windows:
# There is no gem for Windows. Install mysql.so from RubyForApache.
# http://rubyforge.org/projects/rubyforapache
#
# And be sure to use new-style password hashing:
# http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql
database: student
username:
password:
host: localhost

# Warning: The database defined as 'test' will be erased and
# re-generated from your development database when you run 'rake'.
# Do not set this db to the same as development or production.
test:
adapter: mysql
database: student_test
username: root
password:
host: localhost

production:
adapter: mysql
database: student_production
username: root
password:
host: localhost

Now let us write the maintenance application. In a command window type:
c:/rails/work/student>ruby script/generate scaffold Participant Admin

That single command has written a basic maintenance application. The Participant parameter told the command the name of the model we want, and the Admin parameter specifies the name of the controller. Let's try our application. First, we'll start a local WEBrick-based web server, supplied with Rails. Let's connect to it. Remember, the URL we give to our browser contains both the port number (3000) and the name of the controller in lowercase (admin) ie. http://localhost:3000/admin

It's showing us a list of participants, and there aren't any participants. Let's remedy that. Click the New participant link, and a form should appear. Fill in the details and click on the Create button, you should see the new participant in the list. See the screenshot. The User Interface is not good, but it works. We can show this to our client for his/her approval. The client can play with the other links (showing details, editing existing participants etc.).

Rails Scaffolds
A Rails scaffold is an autogenerated framework for manipulating a model. When we run the generator, we tell it that we want a scaffold for a particular model (which it creates) and that we want to access it through a given controller (which it also creates). In Rails, a model is automatically mapped to a database table whose name is the plural form of the model's class. In our case, we asked for a model called Participant, so Rails associated it with the table called participants. And how did it find that table? We told it where to look when we set up the development entry in config/database.yml. When we started the application, the model examined the table in the database, worked out what columns it had, and created mappings between the database data and Ruby objects. We created the participant maintenance scaffolding in the Admin controller, which is why the URL that accesses it has admin at the start of its path. The scaffold is the starting point of an application, not a finished application. And we're about to make use of that fact as we move on to the next iteration in our project.

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

Tuesday, July 11, 2006

Rails and Database Tables

We shall now create a web interface that lets us maintain a student database - create new student records, edit existing student records, delete unwanted ones, and so on. We'll develop this application in small iterations. We'll start off by creating a new Rails application. This is where we'll be doing all our work. Next, we'll create a database to hold our information.

Open a command window and navigate to our folder 'work' where the path on my machine is c:/rails/work Switch to the work folder and use the rails command to create an application called student, as follows.
c:/rails/work>rails student

Create the database student
In a command window type:
c:/rails/work/student>mysql -uroot
You should now get a mysql prompt. Next at the mysql prompt, type as follows:
mysql>create database student;
It will respond with:
Query OK, 1 row affected (0.00 sec)
Next, on the mysql prompt, type:
mysql>grant all on student.* to 'root'@'localhost';
Then type:
mysql>exit

Let's write the Data Definition Language (DDL) for creating the student table in MySQL. Your application student has a sub folder db where we shall store this file create.sql
drop table if exists participants;
create table participants (
id int not null auto_increment,
name varchar(100) not null,
city text not null,
primary key (id)
);
Rails assumes that every table it handles has as its primary key an integer column called id Internally, Rails uses the value in this column to keep track of the data it has loaded from the database and to link between data in different tables.

Now use the mysql client to execute the DDL and create the table in our student database. Type:
c:/rails/work/student>mysql student <db/create.sql
This would have created our participants table.

Rails Naming Convention
Rails assumes that:
  • database table names, like variable names, have lowercase letters and underscores between the words.
  • table names are always plural.
  • files are named in lowercase with underscores.
Rails uses this knowledge of naming conventions to convert names automatically. For example, your application might contain a model class that handles line items. You'd define the class using the Ruby naming convention, calling it LineItem. From this name, Rails would automatically deduce the following.
  • That the corresponding database table will be called line_items. That's the class name, converted to lowercase, with underscores between the words and pluralized.
  • Rails would also know to look for the class definition in a file called line_item.rb (in the app/models directory).
Rails controllers have additional naming conventions. If our application has a store controller, then the following happens.
  • Rails assumes the class is called StoreController and that it's in a file named store_controller.rb in the app/controllers directory.
  • It also assumes there's a helper module named StoreHelper in the file store_helper.rb located in the app/helpers directory.
  • It will look for view templates for this controller in the app/views/store directory.
  • It will by default take the output of these views and wrap them in the layout template contained in store.rhtml or store.rxml in the directory app/views/layouts.
Rails helps by giving you most of the configuration for free if you follow the standard conventions.

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

Sunday, July 09, 2006

Hello, PuneRuby from Rails

Rails being an MVC framework, accepts incoming requests from a browser, decodes the request to find a controller, and calls an action method in that controller. The controller then invokes a particular view to display the results back to the user. Rails takes care of most of the internal plumbing that links all these things together. To write our simple Hello, PuneRuby application, we need code for a controller and a view. We don't need code for a model, as we're not dealing with any data.

Let's use a generator script to create a new controller for our application. This command is called generate, and it lives in the script subdirectory of the demo folder we created. Let's create a controller called Say as follows:
c:/rails/work/demo>ruby script/generate controller Say
The source file we'll be interested in is the controller. You'll find the file say_controller.rb in the folder:
app/controllers/say_controller.rb. Let's have a look at it.
class SayController < ApplicationController
end
SayController is an empty class that inherits from ApplicationController, so it automatically gets all the default controller behavior. We need to add some code to have our controller handle the incoming request. What does this code have to do? For now, it'll do nothing - we simply need an empty action method. Let's add an action called hello to our say controller. Adding a hello action means creating a method called hello in the class SayController. A controller's job is to set up things so that the view knows what to display. In our first application, there's nothing to set up, so an empty action will work fine. Modify say_controller.rb as follow:
class SayController < ApplicationController
def hello
end
end
Now let's try calling it. Find a browser window, and navigate to the URL:
http://localhost:3000/say/hello.
You will see in your browser, a message saying - "Template is Missing." This happens because we created the controller class and the action method, but we haven't told Rails what to display.

By default, Rails looks for templates in a file with the same name as the action it's handling. In our case, that means we need to create a file called hello.rhtml in the folder:
app/views/say/hello.rhtml as follow:
<html>
<head>
<title>Hello, PuneRuby</title>
</head>
<body>
<h1>Hello from PuneRuby!</h1>
</body>
</html>
Save the file hello.rhtml, and refresh your browser window. You should see it display our friendly greeting. Notice that we didn't have to restart the application to see the update. During development, Rails automatically integrates changes into the running application as you save files.

The .rhtml suffix tells Rails to expand the content in the file using a system called ERb (for Embedded Ruby). ERb is a filter that takes an .rhtml file and outputs a transformed version. The output file is often HTML in Rails, but it can be anything. Normal content is passed through without being changed. However, content between <%= and %> is interpreted as Ruby code and executed. The result of that execution is converted into a string, and that value is substituted into the
file in place of the <%=...%> sequence. Here's the modified hello1.rhtml file. In addition, stuff in rhtml between <% and %> (without an equals sign) is interpreted as Ruby code that is executed with no substitution back into the output. The interesting thing about this kind of processing, though, is that it can be intermixed with non-Ruby code. Refresh your browser to see the result.

Let's see how we can link two pages. Add a bye method to the file say_controller.rb as follows:
class SayController < ApplicationController
def hello
end
def bye
end
end
and create the relevant bye.rhtml file as follows:
<html>
<head>
<title>Bye for now</title>
</head>
<body>
<h1>Bye for now</h1>
</body>
</html>


Fire up your browser again, but this time point to the new view using the URL
http://localhost:3000/say/bye.

Now we need to link the two screens together. We'll put a link on the hello screen that takes us to the bye screen, and vice versa. For now we'll use hyperlinks. Rails comes with a bunch of helper methods that can be used in view templates. Here, we'll use the helper method link_to( ), which creates a hyperlink to an action. The file hello2.rhtml shows this:
<html>
<head>
<title>Hello, PuneRuby</title>
</head>
<body>
<h1>Hello from PuneRuby</h1>
<!-- code added for third part of tutorial -->
<br />
<br />
<%= Time.now %>
<br />
<p>
Time to say
<%= link_to "Bye", :action => "bye" %>
</p>
<!-- code added for third part of tutorial -->
</body>
</html>

There's a link_to( ) call within an ERb <%=...%> sequence. This creates a link to a URL that will invoke the bye( ) action. The first parameter in the call to link_to( ) is the text to be displayed in the hyperlink, and the next parameter tells Rails to generate the link to the bye action. As we don't specify a controller, the current one will be used.

Assignment: Create a .rhtml page that links to our page hello2.rhtml Post your solution as comment to this blog post.

First Post | Previous | Next



Technorati Tags:
Blogs linking to this article

Tuesday, July 04, 2006

Verifying Rails Installation

When you install the Rails framework, you also get a new command-line tool, rails, which is used to construct each new Rails application that you write. The rails command creates the right directory structure for you and populates it with some standard Rails code.

We shall create a very small web application to verify our Rails installation.

Open a command window and navigate to a place in your filesystem where you would want to create your application's directory structure. I am creating it in a folder called work and the path on my machine is c:/rails/work Switch to the work folder and use the rails command to create an application called demo, as follows.
c:/rails/work>rails demo

The command has created a directory named demo. Within the demo folder there are many other folders and files created for you. Amongst all of this, you will find a folder called script, that contains some utility scripts that we will be using as we develop our application. For now, we will use the server script that starts a stand-alone web server that can run our newly created Rail application under WEBrick (this is a pure-Ruby web server that comes along with Ruby). So type the command:
c:/rails/work/demo>ruby script/server

We have just started a web server at port 3000. We can now access the application by pointing a browser at http://localhost:3000
You can press control-C to stop WEBrick.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Sunday, July 02, 2006

Ruby on Rails Installation

Armed with the elementary knowledge of Ruby gained so far, I am now going to explore Ruby on Rails. Rails is a full-stack, open-source web framework (support structure) in Ruby, that closely follows the Model View Controller (MVC) architecture for writing real-world applications (Rails applications are written in Ruby) with less code and no cumbersome XML configuration files. Simply put, Rails is an open source Ruby framework for developing database-backed web applications.

To install Ruby on Rails on Windows, we need to do the following:
  • Install Ruby 1.8.2 which we have already done.
  • Check whether you have RubyGems installed by typing gem --version in a command window. We should have this too.
  • Now we'll use RubyGems to install Rails and a few things that Rails needs. Ensure that your internet connection is active. In a command window, type gem install rails --include-dependencies
    Congratulations! You are now on Rails.
  • There's one more step you have to perform before you can start development. Rails works with DB2, MySQL, Oracle, Postgres, SQL Server and SQLite databases. For all but MySQL, you will need to install a database driver, a library that Rails can use to connect to and use your database engine. Rails come with a built-in driver (written in pure Ruby) for MySQL databases. We shall use MySQL 4.1.8 and the installation instructions are in the file mysqlsetup.doc.
  • To update our Rails is simple. In a Command window type: gem update rails RubyGems will automatically update your Rails installation.

I would like all the 42 participants to comment on this post, after they have installed Rails.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Ruby Miscellanea

This is a Work-In-Progress and will cover Ruby Miscellanea topics but relevant to Ruby on Rails.
  1. More on Constants:
    • Constants defined within a class or module may be accessed anywhere within the class or module.
    • Outside the class or module, they may be accessed using the scope operator, :: prefixed by an expression that returns the appropriate class or module.
    • Constants defined outside any class or module may be accessed as it is or by using the scope operator with no prefix.
    • Constants may not be defined in methods.
    • Constants may be added to existing classes and modules from the outside by using the class or module name and the scope operator before the constant name. The program Const.rb shows all of this:
      OUTER_CONST = 99

      class Const
      def get_const
      CONST
      end
      CONST = OUTER_CONST + 1
      end

      puts Const.new.get_const
      puts Const::CONST
      puts ::OUTER_CONST
      puts Const::NEW_CONST = 123
  2. Modules
    Modules are similar to classes in that they hold a collection of methods, constants, and other module and class definitions. Unlike classes, you cannot create objects based on modules.

    Modules serve two purposes:
    • First they act as namespace, letting you define methods whose names will not clash with those defined elsewhere. The examples MyTrig.rb, MyMoral.rb and UseModule.rb illustrates this.
      # MyTrig.rb
      module Trig
      PI = 3.1416
      # class methods
      def Trig.sin(x)
      # ...
      end
      def Trig.cos(x)
      # ...
      end
      end

      # MyMoral.rb
      module Moral
      VERY_BAD = 0
      BAD = 1
      def Moral.sin(badness)
      # ...
      end
      end

      # UseModule.rb
      require 'MyTrig'
      require 'MyMoral'
      y = Trig.sin(Trig::PI/4)
      wrongdoing = Moral.sin(Moral::VERY_BAD)
    • Second, they allow you to share functionality between classes - if a class mixes in a module, that module’s instance methods become available as if they had been defined in the class. They get mixed in. The program Mixins.rb illustrates this:
      # Mixins.rb
      module D
      def initialize(name)
      @name =name
      end
      def to_s
      @name
      end
      end

      module Debug
      include D
      # Methods that act as queries are often
      # named with a trailing ?
      def who_am_i?
      "#{self.class.name} (\##{self.object_id}): #{self.to_s}"
      end
      end

      class Phonograph
      # the include statement simply makes a reference to a named module
      # If that module is in a separate file, use require to drag the file in
      # before using include
      include Debug
      # ...
      end

      class EightTrack
      include Debug
      # ...
      end

      ph = Phonograph.new("West End Blues")
      et = EightTrack.new("Real Pillow")
      puts ph.who_am_i?
      puts et.who_am_i?

  3. Symbols
    A symbol looks like a variable name but it’s prefixed with a colon. Examples: :action, :line_items. You can think of symbols as string literals that are magically turned into constants. Alternatively, you can consider the colon to mean "thing named" so :id is "the thing named id." You can also think of :id as meaning the name of the variable id, and plain id as meaning the value of the variable.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article

Saturday, July 01, 2006

Ruby FAQ



What do you mean by "Ruby is a Dynamic programming language".
In computer science, a dynamic programming language is a kind of programming language in which programs can change their structure as they run: functions may be introduced or removed, new classes of objects may be created, new modules may appear. Refer here for more details.
Can we delete an entry in the middle and shift the remaining entries, in an array?
The delete method of an array can do that, for example:
a = ["a", "b", "b", "c"]
a.delete("b")

The contents of array are now "a" and "c".
Does Ruby have associative arrays like awk?
Hashes (sometimes known as associative arrays, maps or dictionaries) are available in Ruby.
How is memory managed for Strings in Ruby? Is there a separate pool for Strings?
Strings are objects of class String. The String class has more than 75 standard methods. If you refer to Ruby User's Guide, it says that "we do not have to consider the space occupied by a string. We are free from all memory management."
Does Ruby allow us to write functions that can accept variable number of parameters?
Yes. See this example:
def print_nums(*numbers)

end
Can we have an anonymous class in Ruby?
Yes. Refer page 382 of the second edition of the book Programming Ruby, by Dave Thomas
Does Ruby have Multiple Inheritance?
Ruby uses modules to implement mix-ins that simulate multiple inheritance.
Does Ruby allow Object Serialization?
Java features the ability to serialize objects, letting you store them somewhere and reconstitute them when needed. Ruby calls this kind of serialization marshaling. Saving an object and some or all of its components is done using the method Marshal.dump. Later on you can reconstitute the object using Marshal.load. Ruby uses marshaling to store session data.
Java and Ruby Similarities:
As with Java, in Ruby...
  • memory is managed for you via a garbage collector.
  • there’s public, private, and protected methods.
  • you’ve got embedded doc tools (Ruby’s is called RDoc). The docs generated by rdoc look very similar to those generated by javadoc. RDoc can produce fairly good content even if the source contains no comments.
Java and Ruby Differences:
Unlike Java, in Ruby...
  • you don’t need to compile your code. You just run it directly.
  • there’s different GUI toolkits. Ruby users can try WxRuby,
    FXRuby, or the bundled-in Ruby Tk for example.
  • you use the end keyword after defining things like classes, instead of having to put braces around blocks of code.
  • you have require instead of import.
  • all member variables are private. From the outside, you access everything via methods.
  • parentheses in method calls are usually optional and often omitted.
  • everything is an object, including numbers like 2 and 3.14159. Classes are objects! For example, Array is a constant name that is bound to the Array class object. To create a new object, we call new on the class object as in a = Array.new
  • there are no primitives or data types
  • variable names are just labels (not objects). They don’t have a type associated with them.
  • there’s no type declarations. You just assign to new variable names as-needed and they just “spring up” (i.e. a = [1,2,3] rather than int[] a = {1,2,3};).
  • it’s foo = Foo.new( "hi") instead of foo = new Foo( "hi" ).
  • the constructor is always named “initialize” instead of the name of the class.
  • you have “mixin’s” instead of interfaces.
  • YAML tends to be favored over XML.
  • it’s nil instead of null. Also, nil is a normal object; you can never get a null pointer error!
  • there is no method overloading.
  • it's much more common to put many classes in the same file.

This is a work-in-progress.

First Post | Previous | Next


Technorati Tags:
Blogs linking to this article