<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>JavaBeat &#187; Ruby</title>
	<atom:link href="http://www.javabeat.net/category/web-frameworks/ruby/feed/" rel="self" type="application/rss+xml" />
	<link>http://www.javabeat.net</link>
	<description>Java Technology News</description>
	<lastBuildDate>Fri, 24 May 2013 01:32:07 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.5.1</generator>
		<item>
		<title>How to write comments controller using Rails?</title>
		<link>http://www.javabeat.net/2011/04/how-to-write-comments-controller-using-rails/</link>
		<comments>http://www.javabeat.net/2011/04/how-to-write-comments-controller-using-rails/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 12:08:42 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2305</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Rails 3 in Action, to be published Fall 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><a id="dd_start"></a><p><em>This article is based on <a href="http://www.manning.com/katz/" target="_blank">Rails 3 in Action</a>, to be published Fall 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h2 style="text-align: center;">The Comments Controller</h2>
<h2>Introduction</h2>
<p>In a ticket-tracking application, tickets aren’t just there to provide information of a particular problem or suggestion; rather, they’re there to provide the workflow for it. The general workflow of a ticket is that a user will file it and it’ll be classified as a &#8220;new&#8221; ticket. When the developers of the project look at this ticket and decide to work on it, they’ll switch the state on the ticket to &#8220;open&#8221; and once they’re done mark it as &#8220;resolved&#8221;. If a ticket needs more information on it then another state such as &#8220;needs more info&#8221;. A ticket could also be a duplicate of another ticket or it could be something that the developers determine isn’t worthwhile putting in. In cases such as this the ticket may be marked as &#8220;duplicate&#8221; or &#8220;invalid,&#8221; respectively.</p>
<h2>Explanation</h2>
<p>The point here is: tickets have a workflow, and that workflow revolves around state changes. We’ll allow the admin users of this application to add states, but not to delete them. The reason for this is if an admin were to delete a state that was used then we’d have no record of that state ever existing. It’s best if once states are created and used on a ticket that they can’t be deleted.</p>
<p>To track the states, we’d let users leave a comment. With a comment, users will be able to leave a text message about the ticket and may also elect to change the state of the ticket to something else by selecting it from a drop down box. However, not all users will be able to leave a comment and change the state. We will protect both creating a comment and changing the state. By the time we’re done with all of this, the users of our application will have the ability to add comments to our tickets.</p>
<p>In order for a comment form to have somewhere to post we need to generate the CommentsController. We can do this by running this command:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">rails g controller comments</pre></td></tr></table></div>

<p>A create action in this controller will provide the receiving end for the comment form, so we should add this now. We’ll need to define two before_filters in this controller. The first is to ensure the user is signed in because we don’t want anonymous users creating comments for and another to find the Ticket object. This entire controller is shown in listing 1.</p>
<p><strong><span style="color: red;">Listing 1 app/controllers/comments_controller.rb</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">class CommentsController &lt; ApplicationController
before_filter :authenticate_user!
before_filter :find_ticket
def create
@comment = @ticket.comments.build(params[:comment].merge(:user =&gt; current_user))
if @comment.save
flash[:notice] = &quot;Comment has been created.&quot;
redirect_to [@ticket.project, @ticket]
else
flash[:alert] = &quot;Comment has not been created.&quot;
render :template =&gt; &quot;tickets/show&quot;
end
end
private
def find_ticket
@ticket = Ticket.find(params[:ticket_id])
end
end
&nbsp;
&nbsp;
#A redirect_to with array
#B render :template</pre></td></tr></table></div>

<p>In this action we use the template option of render when our @comment.save returns false to render a template of another controller.</p>
<p>You would use the action option to render templates for the current controller. By doing this, the @ticket and @comment objects become available when the app/views/tickets/show.html.erb template is rendered.</p>
<p>If the object saves successfully, we redirect back to the ticket’s page by passing an Array argument to redirect_to, which redirects to a nested route similar to /projects/1/tickets/2.</p>
<p>By creating the controller, we’ve now got all the important parts needed to create comments. Let’s check this feature by running bundle exec cucumber features/creating_comments.feature. We’ll see that it’s able to create the comment but it’s unable to find the text within the #comments element on the page.</p>
<p>Then I should see &#8220;Added a comment!&#8221; within &#8220;#comments&#8221; scope ‘//*[@id = ‘comments’]’ not found on page (Capybara::ElementNotFound)</p>
<p>This is because we haven’t added the comments listing to the show template yet. Let’s do this by adding the code from listing 2 above the comment form.</p>
<p><strong><span style="color: red;">Listing 2 app/views/tickets/show.html.erb</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;h3&gt;Comments&lt;/h3&gt;
&lt;div id=‘comments’&gt;
&lt;% if @ticket.comments.exists? %&gt; &lt;co id=‘ch09_191_1’ /&gt;
&lt;%= render @ticket.comments.select(&amp;:persisted?) %&gt;
&lt;% else %&gt;
There are no comments for this ticket.
&lt;% end %&gt;
&lt;/div&gt;</pre></td></tr></table></div>

<p>Here, we create the element our scenario requires: one with an id attribute of comments. In this we check if there are no comments by using the exists?. This will do a very light query similar to this to check if there are any comments:</p>
<p>SELECT &#8220;comments&#8221;.&#8221;id&#8221; FROM &#8220;comments&#8221; WHERE (&#8220;comments&#8221;.ticket_id = 1) LIMIT 1<br />
It only selects the &#8220;id&#8221; column from the comments table and limits the result set to 1. We could use empty? here instead, but that would load the comments association in its entirety and then check to see if the array is empty. By using exists?, we stop this potential performance issue from cropping up.</p>
<p>Inside this div, if there are comments, we call render and pass it the argument of @ticket.comments and on the end of that call select on it.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p>We use select here because we don’t want to render the comment object we’re building for the form at the bottom of the page. If we left off the select, @ticket.comments would include this new object and render a blank comment box. When we call select on an array, we can pass it a block which it will evaluate on all objects inside that array and return any element which makes the block evaluate to anything that is not nil or false.</p>
<p>The argument we pass to select is called a Symbol-to-Proc and is a shorter way of writing this:<br />
{ |x| x.persisted? }</p>
<p>This is a new syntax versions of Ruby = 1.8.7 and used to be in Active Support in Rails 2. It’s a handy way of writing a short block.</p>
<p>The persisted? method checks if an object is persisted in the database by checking if it has its id attribute set and will return true if that’s the case and false if not.</p>
<p>By using render in this form, Rails will render a partial for every single element in this collection and will try to locate the partial using the first object’s class name. Objects in this particular collection are of the Comment, so the partial Rails will try to find will be at app/views/comments/_comment.html.erb, but we don’t have this file right now. Let’s create it and fill it with the content from listing 3.</p>
<p><strong><span style="color: red;">Listing 3 app/views/comments/_comment.html.erb</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%= div_for(comment) do %&gt;
&lt;h4&gt;&lt;%= comment.user %&gt;&lt;/h4&gt;
&lt;%= simple_format(comment.text) %&gt;
&lt;% end %&gt;</pre></td></tr></table></div>

<p>Here we’ve used a new method, div_for. This method generates a div tag around the content in the block and also sets a class and id attribute based on the object passed in. In this instance, the div tag would be this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;div id=&quot;comment_1&quot; class=&quot;comment&quot;&gt;</pre></td></tr></table></div>

<p>The class method from this tag is used to style our comments so that they will look like figure 1 when the styles from the stylesheet are applied.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2012/04/rails1.jpg"><img class="aligncenter size-medium wp-image-2306" title="rails1" src="http://www.javabeat.net/wp-content/uploads/2012/04/rails1-300x101.jpg" alt="" width="300" height="101" /></a></p>
<p><center><strong><span style="color: red;">Figure 1 A comment</span></strong></center>With this partial now complete, when we run our feature again by running bundle exec cucumber features/creating_comments.feature, it will all be passing!</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">2 scenario (2 passed)
23 steps (23 passed)</pre></td></tr></table></div>

<p>Good to see. We have now got the base for users to be able to change the state of a ticket. Before we proceed further, we should make sure that everything is working as it should by running rake cucumber:ok spec and we should also commit our changes. When we run the tests we’ll see this output:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">47 scenarios (47 passed)
534 steps (534 passed)
# and
23 examples, 0 failures, 7 pending</pre></td></tr></table></div>

<p>Good stuff! Let’s only commit this now.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">git add .
git commit -m &quot;Users can now leave comments on tickets&quot;</pre></td></tr></table></div>

<p>Hey, we’ve got a new file here that begins with capybara in our commit output! This file is the file that was generated by Capybara to show us the page when we used the &#8220;Then show me the page&#8221; step. We should open our .gitignore file and now ignore this file by putting this line in the file:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">capybara*</pre></td></tr></table></div>

<p>This will ignore all capybara files. Let’s remove all the capybara files now and amend this commit and push our changes now.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">git rm capybara*
git commit --amend -m &quot;Users can now leave comments on tickets&quot;
git push</pre></td></tr></table></div>

<p>This newly amended commit will override our previous commit, and the push puts our code on GitHub, where it’s safe. With this push, we’ve completed the first half of our state select feature. We now have added the ability for users of our application to add comments.</p>
<h2>Summary</h2>
<p>We’ve enabled users to leave comments on tickets. This feature is useful because it provides a way for users of a project to have a discussion about a ticket and keep track of it.</p>
<div class='dd_outer'><div class='dd_inner'><div id='dd_ajax_float'><div class='dd_button_v'><script src="http://connect.facebook.net/en_US/all.js#xfbml=1"></script><fb:like href="http%3A%2F%2Fwww.javabeat.net%2Fcategory%2Fweb-frameworks%2Fruby%2Ffeed%2F" send="false" show_faces="false"  layout="box_count" width="50"  ></fb:like></div><div style='clear:left'></div><div class='dd_button_v'><script type='text/javascript' src='https://apis.google.com/js/plusone.js'></script><g:plusone size='tall' href='http://www.javabeat.net/category/web-frameworks/ruby/feed/'></g:plusone></div><div style='clear:left'></div><div class='dd_button_v'><a href="http://twitter.com/share" class="twitter-share-button" data-url="http://www.javabeat.net/category/web-frameworks/ruby/feed/" data-count="vertical" data-text="Ruby" data-via="javabeat" ></a><script type="text/javascript" src="http://platform.twitter.com/widgets.js"></script></div><div style='clear:left'></div><div class='dd_button_extra_v'><script type="text/javascript">jQuery(document).load(function(){ stLight.options({publisher:'bab47279-62c9-46af-addc-79fd1fe8fee0'}); });</script><div class="st_email_custom"><span id='dd_email_text'>email</span></div></div><div style='clear:left'></div><div class='dd_button_extra_v'><div id='dd_print_button'><span id='dd_print_text'><a href='javascript:window:print()'>print</a></span></div></div><div style='clear:left'></div></div></div></div><script type="text/javascript">var dd_offset_from_content = 44; var dd_top_offset_from_content = 0;</script><script type="text/javascript" src="http://www.javabeat.net/wp-content/plugins/digg-digg//js/diggdigg-floating-bar.js?ver=5.3.0"></script><div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/how-to-write-comments-controller-using-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Creating Tags using Rails</title>
		<link>http://www.javabeat.net/2011/04/creating-tags-using-rails/</link>
		<comments>http://www.javabeat.net/2011/04/creating-tags-using-rails/#comments</comments>
		<pubDate>Fri, 15 Apr 2011 00:00:18 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=654</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>This article is based on Rails 3 in Action, to be published Fall 2011. It is being reproduced here by permission from Manning Publications. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><em>This article is based on <a href="http://www.manning.com/katz/" target="_blank">Rails 3 in Action</a>, to be published Fall 2011. It is being reproduced here by permission from <a href="http://www.manning.com" target="_blank">Manning Publications</a>. Manning publishes MEAP (Manning Early Access Program,) eBooks and pBooks. MEAPs are sold exclusively through Manning.com. All pBook purchases include free PDF, mobi and epub. When mobile formats become available all customers will be contacted and upgraded. Visit Manning.com for more information. [ <span style="color: red;"><span style="text-decoration: underline;"><strong>Use promotional code 'java40beat' and get 40% discount on eBooks and pBooks</strong></span> </span>]</em></p>
<h1 style="text-align: center;">Creating Tags</h1>
<h2>Introduction</h2>
<p>Tags in a ticket-tracking application are extremely useful for making similar tickets easier to find and manage. In this article, we will create the interface for adding tags to a new ticket. This involves adding a new field to the new ticket page and defining a has_and_belongs_to_many association between the Ticket model and the not-yet-existent Tag model.</p>
<h2>Creating tags feature</h2>
<p>For this feature, we&#8217;re going to add a text field beneath the description field on the new ticket page, just like we see in figure 1.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/114.jpg"><img class="aligncenter size-full wp-image-1199" title="1" src="http://www.javabeat.net/wp-content/uploads/2011/04/114.jpg" alt="" width="247" height="100" /></a></p>
<p><center><strong><span style="color: red;">Figure 1 The tag box</span></strong></center>The words we enter into this field will become the tags for this ticket and we should see them on the ticket page. At the bottom of features/creating_tickets.feature, we&#8217;ll add a scenario that creates a new ticket with tags, shown in listing 1.</p>
<p><strong><span style="color: red;">Listing 1 features/creating_tickets.feature</span></strong></p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">Scenario: Creating a ticket with tags
When I fill in &quot;Title&quot; with &quot;Non-standards compliance&quot;
And I fill in &quot;Description&quot; with &quot;My pages are ugly!&quot;
And I fill in &quot;Tags&quot; with &quot;browser visual&quot;
And I press &quot;Create Ticket&quot;
Then I should see &quot;Ticket has been created.&quot;
And I should see &quot;browser&quot; in &quot;#ticket #tags&quot;
And I should see &quot;visual&quot; in &quot;#ticket #tags&quot;</pre></td></tr></table></div>

<p>When we run this scenario using bundle exec cucumber, it will fail features/creating_tickets.feature:48 declaring that it can&#8217;t find the &#8220;Tags&#8221; field. Good! It&#8217;s not there yet.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">And I fill in &quot;Tags&quot; with &quot;browser visual&quot;
cannot fill in, no text field, text area or password field
with id, name, or label 'Tags' found (Capybara::ElementNotFound)</pre></td></tr></table></div>

<p>We&#8217;re going to need to take the data from this field and process each word into a new Tag object and, for that reason, we&#8217;ll use a text_field_tag to render this field. text_field_tag is similar to a text_field tag, but it doesn&#8217;t have to relate to any specific object like text_field does; instead it will just output an input tag with the type attribute set to &#8220;text&#8221; and the name set to whatever name we give it.</p>
<h2>Using text_field_tag</h2>
<p>To define this field, we will put the following code underneath the p tag for the description in app/views/tickets/_form.html.erb.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%= f.label_tag :tags %&gt;
&lt;%= f.text_field_tag :tags, params[:tags] %&gt;</pre></td></tr></table></div>

<p>This field will be sent through to TicketsController as simply params[:tags]. By specifying params[:tags] as the second argument to this method, we can repopulate this field when the ticket cannot be created due to it failing validation.</p>
<p>When we re run this scenario, it no longer complains about the missing &#8220;Tags&#8221; field, but now that it can&#8217;t find the tags area for our ticket:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">And I should see &quot;browser&quot; within &quot;#ticket #tags&quot;
scope '//*[@id = 'ticket']//*[@id = 'tags']' not found ...</pre></td></tr></table></div>

<p>We will need to define a #tags element inside the #ticket element so that this part of the scenario will pass. This element will contain the tags for our ticket, which our scenario will assert as actually visible.</p>
<h2>Showing tags</h2>
<p>We can add this new element to app/views/tickets/show.html.erb by adding this simple line underneath where we render the ticket&#8217;s description:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;div id='tags'&gt;&lt;%= render @ticket.tags %&gt;&lt;/div&gt;</pre></td></tr></table></div>

<p>This creates the #ticket #tags element our feature is looking for and will render the soon-to-be-created app/views/tags/_tag.html.erb partial for every element in the also-soon-to-be-created tags association on the @ticket object.</p>
<p>So what out of these two steps is our next one? We can run our scenario again to see that it cannot find the tags method for a Ticket object:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">undefined method 'tags' for #&lt;Ticket:0x0..</pre></td></tr></table></div>

<p>This method is the tags method, which we&#8217;ll be defining with a has_and_belongs_to_many association between Ticket objects and Tag objects. It will be responsible for returning a collection of all the tags associated with the given ticket, much like a has_many would. It works in the opposite direction also: allowing us to find out what tickets have a specific tag.</p>
<h2>Defining the tags association</h2>
<p>We can define the association has_and_belongs_to_many on the Ticket model by using this line, placed after a new line after the has_many definitions inside our Ticket model:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">has_and_belongs_to_many :tags</pre></td></tr></table></div>

<p>This association will rely on a join table that doesn&#8217;t yet exist, called tags_tickets. This table contains only two fields, which are both foreign keys for tags and tickets. By using a join table, many tickets can have many tags, and vice versa.</p>
<p>When we rerun our scenario we&#8217;re told that there&#8217;s no constant called Tag yet:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">uninitialized constant Ticket::Tag (ActionView::Template::Error)</pre></td></tr></table></div>

<p>In other words, there is no Tag model yet. We should define this now if we want to go any further.</p>
<h2>The Tag model</h2>
<p>Our Tag model will have a single field called name which should be unique. To generate this model and its related migration we will run the rails command like this:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;"> rails g model tag name:string --timestamps false</pre></td></tr></table></div>

<p>The timestamps option passed here determines whether or not the model&#8217;s migration is generated with timestamps. Because we&#8217;ve passed the value of false to this, there will be no timestamps added.</p>
<p>Before we run this migration, we will need to add the join table called tags_tickets to our database, which has two fields: one called ticket_id and the other tag_id. The table name is the pluralized names of the two models it is joining, sorted in alphabetical order. This table will have no primary key as we only need it to join the tags and tickets table. We are never going to look for individual records from this table.</p>
<p>To define the table we will put this tags_tickets in the self.up section of our db/migrate/[timestamp]_create_tags.rb migration:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">create_table :tags_tickets, :id =&gt; false do | t |
t.integer :tag_id, :ticket_id
end</pre></td></tr></table></div>

<p>The :id =&gt; false option passed to create_table here tells Active Record to create the table without the id field.</p>
<p>We should also add drop_table :tag_tickets to the self.down method in this migration too so that, if we need to, we can undo this migration. Next, we will run the migration on our development database by running rake db:migrate and our test database by running rake db:test:prepare. This will create the tags and tags_tickets tables. When we run this scenario again with bundle exec cucumber features/creating_tickets:48, it is now satisfied that the tags method is defined and has now moved on to whining that it can&#8217;t find the tag we specified:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">And I should see &quot;browser&quot; within &quot;#ticket #tags&quot;
Failed assertion, no message given. (MiniTest::Assertion)</pre></td></tr></table></div>

<p>This is because we&#8217;re not doing anything to associate the text from the &#8220;Tags&#8221; field to the ticket we&#8217;ve just created. We need to parse the content from this field into new Tag objects and then associate them with the ticket we are creating, which we&#8217;ll look at how to do right now.</p>
<h2>Displaying a ticket&#8217;s tags</h2>
<p>The params[:tags] in TicketsController&#8217;s create is the value from our &#8220;Tags&#8221; field on app/views/tickets/_form.html.erb. This is also the field we need to parse into Tag objects and associate them with the Ticket object we are creating.</p>
<p>To do this, we will alter the create action by adding this line directly after @ticket.save:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">@ticket.tag!(params[:tags])</pre></td></tr></table></div>

<p>This method will parse the tags from params[:tags], convert them into new Tag objects, and associate them with the ticket. We can define this new method at the bottom of our Ticket model like this:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">def tag!(tags)
tags = tags.split(&quot; &quot;).map do |tag|
Tag.find_or_create_by_name(tag)
end
self.tags &lt;&lt; tags
end</pre></td></tr></table></div>

<p>On the first line here, we use the split method to split our string into an array, and then the map method to iterate through every value in the array. Inside the block for map, we use a dynamic finder to find or create a tag with a specified name. find_or_create_by methods will always return a record, whether it be a preexisting or a recently created one.</p>
<p>After all the tags have been iterated through, we assign them to a ticket by using the &lt;&lt; method on the tags association. The tag! method we have just written will create the tags that we will display on the app/views/tickets/show.html.erb view by using this line:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;%= render @ticket.tags %&gt;</pre></td></tr></table></div>

<p>When we run this scenario again by running bundle exec cucumber features/creating_tickets.feature:48, we will see it&#8217;s this line that is failing with an error:<br />
Missing partial tags/tag &#8230;</p>
<p>Therefore, the next step is to write the tag partial, which our feature has just complained about. To do this, we will put the following code in app/views/tags/_tag.html.erb:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;span class='tag'&gt;&lt;%= tag.name %&gt;&lt;/span&gt;</pre></td></tr></table></div>

<p>By wrapping the tag name in a span with the of tag, class, it will be styled as defined in our stylesheet. With this partial defined, this puts the final piece of the puzzle for this feature into place. When we run our scenario again by running bundleexeccucumber features/creating_tickets.feature:48 it passes:</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">1 scenario (1 passed)
15 steps (15 passed)</pre></td></tr></table></div>

<p>Great! This scenario is now complete. When a user creates a ticket, they are able to assign tags to that ticket and they display along with the ticket&#8217;s information on the show action for TicketsController.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2011/04/211.jpg"><img class="aligncenter size-full wp-image-1198" title="2" src="http://www.javabeat.net/wp-content/uploads/2011/04/211.jpg" alt="" width="227" height="150" /></a></p>
<p><center><strong><span style="color: red;">Figure 1 Look ma, a tag!</span></strong></center>We will now commit this change, but, of course, before we do, we&#8217;ll ensure that we haven&#8217;t broken anything by running rake cucumber:ok spec.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">53 scenarios (53 passed)
620 steps (620 passed)
# and
27 examples, 0 failures, 10 pending</pre></td></tr></table></div>

<p>Good to see that nothing&#8217;s blown up this time. Let&#8217;s commit this change.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">git add .
git commit -m &quot;Users can tag tickets upon creation&quot;
git push</pre></td></tr></table></div>

<p>Now that users are able to add a tag to a ticket when that ticket&#8217;s being created, we should also let them add tags to a ticket when they create a comment as well.</p>
<p>When a ticket&#8217;s discussion happens, new information may come about that would require that another tag be added to the ticket to group it into a different set. A perfect way to let our users do this would be to let them add it when they comment.</p>
<h2>Summary</h2>
<p>We&#8217;ve covered how to use a has_and_belongs_to_many association to define a link between tickets and tags. Tickets are capable of having more than one tag, but a tag is also capable of having more than one ticket assigned to it and, therefore, we use this type of association. A has_and_belongs_to_many could be used to associate people and the locations they&#8217;ve been.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2011/04/creating-tags-using-rails/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Creating Database aware applications in Ruby on Rails</title>
		<link>http://www.javabeat.net/2010/12/creating-database-aware-applications-in-ruby-on-rails/</link>
		<comments>http://www.javabeat.net/2010/12/creating-database-aware-applications-in-ruby-on-rails/#comments</comments>
		<pubDate>Mon, 06 Dec 2010 01:28:03 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Ruby on Rails]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=526</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction In this article, we will explore the capabilities of Ruby with respect to the Data Tier. One can understand the power of Ruby which greatly simplifies the development of data aware applications after reading this article. This is mainly because of the abstraction introduced in Ruby in the form of Active Record. Active Record [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p align="justify">In this article, we will explore the capabilities of <strong>Ruby</strong> with respect to the Data Tier. One can understand the power of <strong>Ruby</strong> which greatly simplifies the development of data aware applications after reading this article. This is mainly because of the abstraction introduced in <strong>Ruby</strong> in the form of Active Record. Active Record defines the object relational mapping between <strong>Ruby</strong> objects and Database tables. The first section of this article will deal with Active Record and how to work with CRUD operations using it. The later section of the article guides in developing a full-blown web application using the Active Record API.</p>
<h2>Download Example Source Code</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2010/201012-database-aware-applications-ruby-on-rails.zip">Download Ruby on Rails Sample Code</a></li>
</ul>
<h2>Active Record Basics</h2>
<p align="justify">There are various implementations for Object Relation mapping model available in <strong>Ruby</strong>. One such popular implementation is Active Record. Usage of Active Record API in an application will lead to writing fewer lines of code. Active Record also provides various utility classes for directly creating tables from the application using simpler syntax. The mapping between <strong>Ruby</strong> classes and database tables can be elegantly done. Active Record follows the convention of having plaral names for the table name and singular name for the class names. For example, one can say that the class &#8216;Employee&#8217; will map directly to &#8216;employees&#8217; table in Active Record context. It is also possible to dynamically generate method names through Active Record, the example of which will be seen later in this article.</p>
<h3>Creating records</h3>
<p align="justify">In this section, we will see the basics of using Active Record API. More specifically we will see how to map <strong>Ruby</strong> classes and database table for creating records in the database. Note that this example using MySql database, so make sure before using the application, a compatible version of MySql gem is installed in your machine.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">require &quot;logger&quot;
&nbsp;
require &quot;rubygems&quot;
require &quot;active_record&quot;
require &quot;pp&quot;
&nbsp;
ActiveRecord::Base.logger = Logger.new(STDOUT)
&nbsp;
ActiveRecord::Base.establish_connection(:adapter =&gt; &quot;mysql&quot; ,
:database =&gt; &quot;ruby&quot;, :username =&gt; &quot;root&quot;, :password =&gt; &quot;XXX&quot;)
&nbsp;
class Bank &lt; ActiveRecord::Base
end
&nbsp;
Bank.delete_all
&nbsp;
hdfc_bank = Bank.new();
hdfc_bank.id = '1';
hdfc_bank.name = &quot;HDFC Bank&quot;;
hdfc_bank.operation_date = Date.today;
hdfc_bank.head_office = &quot;Mumbai&quot;;
hdfc_bank.save;
puts (&quot;HDFC Bank object created&quot;);
&nbsp;
sbi_bank = Bank.new();
sbi_bank.id = '2';
sbi_bank.name = &quot;SBI Bank&quot;;
sbi_bank.operation_date = Date.today;
sbi_bank.head_office = &quot;Bangalore&quot;;
sbi_bank.save;
puts (&quot;SBI Bank object created&quot;);
&nbsp;
icici_bank = Bank.new();
icici_bank.id = '3';
icici_bank.name = &quot;ICICI Bank&quot;;
icici_bank.operation_date = Date.today;
icici_bank.head_office = &quot;Delhi&quot;;
icici_bank.save;
puts (&quot;ICICI Bank object created&quot;);</pre></td></tr></table></div>

<p align="justify">The first few statements import the necessary dependencies packages such as &#8216;logger&#8217; and &#8216;active_record&#8217;. We have defined a logger that points to the standard console. A connection is established to the MySql database using the method call &#8216;establish_connection&#8217; by passing in the database adapter name, the database name and username/password details. It is assumed that a table with the name &#8216;banks&#8217; exist in the database for this example. Next we have defined a class called &#8216;Bank&#8217; which extends from &#8216;ActiveRecord::Base&#8217;. This single line will ensure that a mapping is established between the <strong>Ruby</strong> class &#8216;Bank&#8217; and the database table &#8216;banks&#8217;.</p>
<p align="justify">Since the Bank class extends from &#8216;ActiveRecord::Base&#8217;, most of the common database CRUD operations become implicitly available to the Bank class. One such operation is delete_all() which will remove all the bank records from the database. Note that the banks table has the columns &#8216;ID&#8217;, &#8216;NAME&#8217;, &#8216;OPERATION_DATE&#8217; and &#8216;HEAD_OFFICE&#8217; which will directly map to the properties &#8216;id&#8217;, &#8216;name&#8217;, &#8216;operation_date&#8217; and &#8216;head_office&#8217; of the Bank class.<br />
A new empty bank record is created using the statement Bank.new(), after that we initialize various properties of the bank object. A call to save() on the Bank object will persist the entity to the database.</p>
<h3>Finding Records</h3>
<p align="justify">In the previous section, we have seen how to use the Active Record API for inserting data into the database. In this section, we will see how to find data using easy-to-use predefined data-aware methods.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">require &quot;logger&quot;
&nbsp;
require &quot;rubygems&quot;
require &quot;active_record&quot;
require &quot;pp&quot;
&nbsp;
ActiveRecord::Base.logger = Logger.new(STDOUT)
&nbsp;
ActiveRecord::Base.establish_connection(:adapter =&gt; &quot;mysql&quot; ,
:database =&gt; &quot;ruby&quot;, :username =&gt; &quot;root&quot;, :password =&gt; &quot;XXX&quot;)
&nbsp;
class Bank &lt; ActiveRecord::Base
&nbsp;
end
&nbsp;
&nbsp;
bank_object = Bank.find(:first)
puts (&quot;Id is #{bank_object.id}&quot;);
puts (&quot;Name is #{bank_object.name}&quot;);
&nbsp;
&nbsp;
bank_object = Bank.find(:last)
puts (&quot;Id is #{bank_object.id}&quot;);
puts (&quot;Name is #{bank_object.name}&quot;);
&nbsp;
bank_object = Bank.find(2)
puts (&quot;Id is #{bank_object.id}&quot;);
puts (&quot;Name is #{bank_object.name}&quot;);
&nbsp;
all_banks = Bank.find_by_sql(&quot;select * from banks&quot;);
for bank in all_banks
	puts (&quot;#{bank.name}&quot;);
end
&nbsp;
&nbsp;
sbi_bank = Bank.find_by_name(&quot;SBI Bank&quot;);
puts (&quot;Name is #{sbi_bank.name}&quot;);
&nbsp;
icici_bank = Bank.find_by_head_office(&quot;Delhi&quot;);
puts (&quot;Name is #{icici_bank.name}&quot;);
&nbsp;
Bank.find(:all).each do |bank|
puts &quot;#{bank.name}&quot;
end</pre></td></tr></table></div>

<p align="justify">The constants &#8216;:first&#8217; and &#8216;:last&#8217; carry special meaning in the context of Active Record and when used willl fetch the first and the last records from the database when used in tandem with the find() method. It is also possible to retrieve the data using the primary key value. We have used find() by passing in a value of 2, in this case a comparison will happen between the primary key column with 2. Other variations for finding the objects are through queries and dynamic methods. For example, in the above code, we have used the query for fetching all the bank objects from the database. Another using strategy for retrieving data from the database is to use find_by_&lt;property_name&gt; notation. This means, it is possible to use the methods find_by_name(), find_by_head_office(), find_by_operation_date() directly on the bank obejcts by passing in the appropriate property value.</p>
<h3>Edit Records</h3>
<p align="justify">Having seen the usage of Create and Find, we will see how to use Active Record for editing persistent objects, the following code snippet will illustrate the usage.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">require &quot;logger&quot;
&nbsp;
require &quot;rubygems&quot;
require &quot;active_record&quot;
require &quot;pp&quot;
&nbsp;
ActiveRecord::Base.logger = Logger.new(STDOUT)
&nbsp;
ActiveRecord::Base.establish_connection(:adapter =&gt; &quot;mysql&quot; ,
:database =&gt; &quot;ruby&quot;, :username =&gt; &quot;root&quot;, :password =&gt; &quot;XXX&quot;)
&nbsp;
class Bank &lt; ActiveRecord::Base
&nbsp;
end
&nbsp;
bank = Bank.find(1);
bank.name = &quot;HDFC&quot;;
bank.save;
&nbsp;
Bank.update_all(&quot;head_office = 'New Location'&quot;);
&nbsp;
Bank.delete_all();</pre></td></tr></table></div>

<p align="justify">We have used a flavour of find() method to retrieve the object from the database, and then have updated its properties using the regular approach. A call to save() will now update the corresponding entity in the database, instead of creating a new entity. Likewise, there are other useful methods such as update_all() and delete_all(). A call to update_all() which accept an expression, in the example case we have used &#8216;head_office = New Location&#8217;, this will make all the head_office column values to have the value &#8216;New Location&#8217;. Similarly delete_all() will remove all the records from the database.</p>
<h3>Establishing relationship</h3>
<p align="justify">Complex relationship between objects as well as its corresponding mapping at the database level can be easily achieved using Active Record. The following example illustrates the usage of relationship between the objects blogs and posts. A blog can have multiple posts and each post must know to which blog it belongs to.</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">require &quot;logger&quot;
&nbsp;
require &quot;rubygems&quot;
require &quot;activerecord&quot;
&nbsp;
ActiveRecord::Base.logger = Logger.new(STDOUT)
&nbsp;
ActiveRecord::Base.establish_connection(:adapter =&gt; &quot;mysql&quot; ,
:database =&gt; &quot;ruby&quot;, :username =&gt; &quot;root&quot;, :password =&gt; &quot;XXX&quot;)
&nbsp;
ActiveRecord::Schema.define do
&nbsp;
  create_table :blogs, :force =&gt; true do |b|
    b.string   :name     
    b.string   :title
    b.string   :description
  end
&nbsp;
  create_table :posts, :force =&gt; true do |p|
    p.integer :blog_id
    p.text    :description
  end
end
&nbsp;
&nbsp;
class Blog &lt; ActiveRecord::Base
  has_many :posts
end
&nbsp;
&nbsp;
class Post &lt; ActiveRecord::Base
  belongs_to :blog
end
&nbsp;
&nbsp;
Post.delete_all();
Blog.delete_all();
&nbsp;
java_blog = Blog.create(
	:name =&gt; &quot;Java Blog&quot;, :title =&gt; &quot;Java beat Blog&quot;, :description =&gt; &quot;Contains Java Articles and Tips&quot;
)
post1 = Post.new();
post1.id = 'P1'
post1.description = 'Java Articles are great';
post1.blog = java_blog;
post1.save;
&nbsp;
&nbsp;
post2 = Post.new();
post2.id = 'P2'
post2.description = 'Java Tips are very useful';
post2.blog = java_blog;
post2.save;
&nbsp;
cpp_blog = Blog.create(
	:name =&gt; &quot;CPP Blog&quot;, :title =&gt; &quot;CPP Blog&quot;, :description =&gt; &quot;Contains CPP Articles and Tips&quot;
)
post3 = Post.new();
post3.id = 'P3'
post3.description = 'CPP Articles are great';
post3.blog = cpp_blog;
post3.save;
&nbsp;
&nbsp;
post4 = Post.new();
post4.id = 'P4'
post4.description = 'CPP Tips are very useful';
post4.blog = cpp_blog;
post4.save;</pre></td></tr></table></div>

<p align="justify">The above example also illustrates the usage of Active Record&#8217; Schema for creating tables and relationships directly from the application. The keywords &#8216;has_many&#8217; defines a one to many relationship between Blog and Post objects and &#8216;belong_to&#8217; ensures that the master reference Blog is preserved in the Post object. After running the application, the table structure will look something similar to the following,</p>

<div class="wp_syntax"><table><tr><td class="line_numbers"><pre>1
</pre></td><td class="code"><pre class="language" style="font-family:monospace;">&lt;strong&gt;Blog&lt;/strong&gt; Id Name Title Description 1 Java Blog Java beat Blog 2 CPP Blog CPP Blog &lt;strong&gt;Post&lt;/strong&gt; Id Blog Id Description 1 1 Java Articles are great 2 1 Java Tips are very useful 3 2 CPP Articles are great 4 2 CPP Tips are very useful</pre></td></tr></table></div>

<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/12/creating-database-aware-applications-in-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Cloning Internet Applications with Ruby</title>
		<link>http://www.javabeat.net/2010/10/cloning-internet-applications-with-ruby/</link>
		<comments>http://www.javabeat.net/2010/10/cloning-internet-applications-with-ruby/#comments</comments>
		<pubDate>Thu, 28 Oct 2010 00:29:01 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1649</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Cloning Internet Applications with Ruby We stand on the shoulders of giants. This has been true since the time of Newton (and even before) and it is certainly true now. Much of what we know and learn of programming, we learnt from the pioneering programmers before us and what we leave behind to future generations [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>Cloning Internet Applications with Ruby</CENTER></H1><br />
<P>We stand on the shoulders of giants. This has been true since the time of Newton (and<br />
even before) and it is certainly true now. Much of what we know and learn of<br />
programming, we learnt from the pioneering programmers before us and what we leave<br />
behind to future generations of programmers is our hard-earned experience and precious<br />
knowledge. This book is all about being the scaffolding upon which the next generation<br />
of programmers stands when they build the next Sistine Chapel of software.</P><br />
<P>There are many ways that we can build this scaffolding but one of the best ways is simply<br />
to copy from what works. Many programming books attempt to teach with code samples<br />
that the readers can reproduce and try it out themselves. This book goes beyond code<br />
samples. The reader doesn’t only copy snippets of code or build simple applications but<br />
have a chance to take a peek at how a few of the most popular Internet applications today<br />
can possibly be built. We explore how these applications are coded and also the rationale<br />
behind the way they are designed. The aim is to guide the programmer through the steps<br />
of building clones of the various popular Internet applications.</P><br />
<H1>What This Book Covers</H1><br />
<P><I>Chapter 1, Cloning Internet Applications</I> gives a brief description of the purpose of the<br />
book, the target readers of the book, and a list of the four popular Internet applications we<br />
will be cloning in the subsequent chapters. The bulk of this chapter gives a brief rundown<br />
on the various technologies we will be using to build those clones.</P><br />
<P><I>Chapter 2, URL Shorteners – Cloning TinyURL</I> explains about the first popular Internet<br />
application that we investigate and clone in the book, which is TinyURL. This chapter<br />
describes how to create a TinyURL clone, its basic principles, and algorithms used</P><br />
<P><I>Chapter 3, Microblogs – Cloning Twitter</I>. The clone in this chapter emulates one of the<br />
hottest and most popular Internet web applications now—Twitter. It describes the basic<br />
principles of a microblogging application and explains how to recreate a feature-complete<br />
Twitter clone.</P><br />
<P><I>Chapter 4, Photo -sharing – Cloning Flickr</I>. Flickr is one of the most popular and<br />
enduring photo-sharing applications on the Internet. This chapter describes how the<br />
reader can re-create a feature complete photo-sharing application the simplest way<br />
possible, following the interface and style in Flickr.</P><br />
<P><I>Chapter 5, Social Networking Services – Cloning Facebook 1</I>. The final two chapters<br />
describe the various aspects of Internet social networking services, focusing on one of the<br />
most popular out there now—Facebook. These two chapters also describe the minimal<br />
features of a social networking service and show the reader how to implement these<br />
features in a complete step-by-step guide. The first part is described in this chapter, which<br />
sets the groundwork for the clone and proceeds to describe the data model used in the<br />
clone.</P><br />
<P><I>Chapter 6, Social Networking Services – Cloning Facebook 2</I>. The final chapter is part<br />
two in describing how to create a Facebook clone. This chapter follows on the previous<br />
chapter and describes the application flow of the Facebook clone we started earlier.</P><br />
<H1><CENTER>Social Networking Services – Cloning Facebook 1</CENTER></H1><br />
<P>One of the most dominant Internet services today is the social networking service.<br />
According to a report by the Nielsen Company, in January 2010, the amount of time<br />
an average person spent on Facebook is more than seven hours per month, which<br />
amounts to more than 14 minutes per day. If you lump together the time spent<br />
on Google, Yahoo!, YouTube, Bing, Wikipedia, and Amazon, it still doesn&#8217;t beat<br />
Facebook! By March 2010, Facebook accounted for more than seven percent of all<br />
Internet traffic in the United States, surpassing visits to Google. Social networking<br />
services have risen in the past few years to be more than just a passing fad, to be an<br />
important communications tool as well as a part of daily life.</P><br />
<P>We will be building our last and most complex clone based on Facebook, the most<br />
popular social networking service as of date. The clone we will build here will<br />
be described over this and the next chapter. In this chapter we will cover basic<br />
information about social networking services, main features of the clone that we will<br />
build, as well as the description of the data model we will be using for the clone.</P><br />
<H1>All about social networking services</H1><br />
<P>A social networking service is an Internet service that models social relationships<br />
among people. Essentially it consists of a user profile, his or her social links, and<br />
a variety of additional services. Most social networking services are web-based<br />
and provide various ways for users to interact over the Internet, including sharing<br />
content and communications.</P><br />
<P>Early social networking websites started in the form of generalized online<br />
communities such as The WELL (1985), theglobe.com (1994), GeoCities (1994), and<br />
Tripod (1995). These early communities focused on communications through chat<br />
rooms, and sharing personal information and topics via simple publishing tools.<br />
Other communities took the approach of simply having people link to each other<br />
via e-mail addresses. These sites in cluded Classmates (1995), focusing on ties with<br />
former schoolmates, and SixDegrees (1997), focusing on indirect ties.</P><br />
<P>SixDegrees.com in a way was the first to bring together the first few defining features<br />
of a social networking service. The basic features of the first online social networking<br />
services include user profiles, adding friends to a friends list, and sending private<br />
messages. Unfortunately, SixDegrees was too advanced for its time and eventually<br />
closed in 2001.</P><br />
<P>Interestingly the most popular social networking service in Korea, CyWorld, was<br />
started around this time in 1999. The original intention for CyWorld was to develop<br />
an online dating service similar to Match and provide an open public meeting place<br />
for users to meet online. In 2001, CyWorld launched the minihompy service, a<br />
feature that allows each user to create a virtual homepage. This was highly successful<br />
as celebrities and politicians took to this platform to reach out to their fans and<br />
audience. CyWorld also eventually included a virtual currency called &#8220;dottori&#8221; in<br />
2002 and a mobile version in 2004. Up to 2008, CyWorld had more than one third of<br />
Korea&#8217;s entire population as members with a strong penetration of ninety percent in<br />
the young adults market.</P><br />
<P>Between 2002 and 2004, a few social networking services became highly popular.<br />
Friendster, started by Jon Abraham in 2002 to compete with Match .com , was highly<br />
successful initially. However due to platform and scalability issues, its popularity<br />
plummeted as newer social networking services were launched. MySpace ,<br />
launched in 2003, was started as a Friendster alternative and became popular with<br />
independent rock bands from Los Angeles as promoters used the platform to<br />
advertise VIP passes for popular clubs. Subsequently, MySpac e facilitated a two-way<br />
conversation between bands and their fans, and music became the growth engine of<br />
MySpace. MySpace also introduced the concept of allowing users to personalize<br />
their pages and to generate unique layouts and backgrounds. Eventually MySpace<br />
became the most dominant social networking service in U.S. until Facebook took<br />
over in 2009.</P><br />
<P>Mixiis the largest online social networking service in Japan with a total of 20 million<br />
users to date and over ninety percent of users being Japanese. Launched in February<br />
2004 by founder KenjiKasahara, the focus of Mixiis to enable users to meet new<br />
people who share common interests. An interesting feature of Mixi(counterintuitive)<br />
is that it&#8217;s an <I>invitation by friend</I> social network, which means that a new user can<br />
only join Mixithrough an invitation by an existing user. This feature is only found<br />
in niche and private social networks such as http://www.asmallworld.net, a<br />
successful social networking service that caters to celebrities and high net worth<br />
individuals. This invitation-based model holds the user responsible for who they<br />
invite, and thus reduces unwanted behavior within the network, refl ecting Japanese<br />
culture itself.</P><br />
<P>Social networking began to emerge as a part of business Internet strategy at around<br />
2005 when Yahoo! launched Yahoo! 360 , its first attempt at a social networking<br />
service. In July 2005 News Corporation bought MySpace. It was around this time as<br />
well that the first mainland Chinese social networks started. The three most notable<br />
examples in chronological order are 51.com (2005), Xiaonei(2005), and Kaixin001<br />
(2008). 51.com drew its inspiration from CyWorld, and later MySpace and QQ. On<br />
the other hand, Xiaoneihas a user interface that follows Facebook, though it also<br />
offers the user flexibility to change the look and feel, similar to MySpace. Kaixin001,<br />
the latest social networking platform in China with the fastest growing number of<br />
users, started in 2008 and the platform and user interface are remarkably similar<br />
to Facebook.</P><br />
<P>It was also around this time that more niche social networking services focusing on<br />
specific demographics sprang up, with the most successful example being LinkedIn,<br />
which focused on business professionals. At the same time media content sharing<br />
sites began slowly incorporated social networking service features and became social<br />
networking services themselves. Examples include QQ (instant messaging), Flickr<br />
(photo-sharing), YouTube (video-sharing), and Last.FM (music sharing).</P><br />
<P>As mentioned earlier, as of early 2010 social networking services are the dominant<br />
service and purpose for many users on the Internet, with Internet traffic in US<br />
surpassing the previous giant of the Internet.</P><br />
<H2>Facebook</H2><br />
<P>Facebook is the most dominant social networking service till date, with 400 million<br />
active users, 5 billion pieces of content shared each week, and more than 100 million<br />
active users concurrently accessing Facebook through their mobile devices.<br />
It is also the most widespread, with 70 percent of its users from outside of US, its<br />
home market.</P><br />
<P>Mark Zuckerberg and some of his Harvard college roommates launched Facebook<br />
in February 2004. Initially intended as an online directory for college students (the<br />
initial membership was limited to Harvard College students) it was later expanded<br />
to include other colleges, then high schools, and finally anyone around the world<br />
who is 13 years old and above.</P><br />
<P>Facebook features are typically that of many social networks that were created<br />
around that time. The more prominent ones are the Wall (a space on every user&#8217;s<br />
profile five friends to post messages on), pokes (which allows users to virtually<br />
<I>poke</I> each other, that is to notify a user that they have been <I>poked</I>), photo uploading,<br />
sharing, and status updates, which allow users to inform their friends of their<br />
whereabouts and what they were doing. Over time, Facebook included features to<br />
form virtual groups, to blog, to start events, chat with instant messaging, and even<br />
send virtual gifts to friends.</P><br />
<P>Facebook launched Facebook Platform in May 2007, providing a framework for<br />
software developers to create applications that interact with Facebook. It soon<br />
became wildly popular, and within a year 400,000 developers have registered<br />
for the platform, and built 33,000 applications. As of writing date there are more<br />
than 500,000 active applications in Facebook, developed by more than 1 million<br />
developers and there are more than 250 applications with more than 1 million<br />
monthly active users!</P><br />
<P>In this chapter we will be cloning Facebook and creating an application called<br />
Colony, which has the basic but essential features of Facebook.</P><br />
<H1>Main features</H1><br />
<P>Online social networking services are complex applications with a large number<br />
of features. However, these features can be roughly grouped into a few<br />
common categories:</P><br />
<UL><br />
<LI>User</LI><br />
<LI>Community</LI><br />
<LI>Content-sharing</LI><br />
<LI>Developer</LI><br />
</UL><br />
<P>User features are features that relate directly to and with the user. For example,<br />
the ability to create and share their own profiles, and the ability to share status and<br />
activities are user features. Community features are features that connect users with<br />
each other. An example of this is the friends list feature, which shows the number of<br />
friends a user has connected with in the social network.</P><br />
<P>Content sharing features are quite easy to understand. These are features that<br />
allow a user to share his self-created content with other users, for example photo<br />
sharing or blogging. Social bookmarking features are those features that allow users<br />
to share content they have discovered with other users, such as sharing links and<br />
tagging items with labels. Finally, developer features are features that allow external<br />
developers to access the services and data in the social networks.</P><br />
<P>While the social networking services out in the market often try to differentiate<br />
themselves from each other in order to gain an edge over their competition, in this<br />
chapter we will be building a stereotypical online social networking service. We will<br />
be choosing only a few of the more common features in each category, except for<br />
developer features, which for practical reasons will not be implemented here.</P><br />
<P>Let&#8217;s look at these features we will implement in Colony, by category.</P><br />
<H2>User</H2><br />
<P>User features are features that relate directly to users:</P><br />
<UL><br />
<LI>Users&#8217; activities on the system are broadcast to friends as an activity feed.</LI><br />
<LI>Users can post brief status updates to all users.</LI><br />
<LI>Users can add or remove friends by inviting them to link up. Friendship in<br />
both ways need to be approved by the recipient of the invitation.</LI><br />
</UL><br />
<H2>Community</H2><br />
<P>Community features connect users with each other:</P><br />
<LI>Users can post to a wall belonging to a user, group, or event. A wall is a place<br />
where any user can post on and can be viewed by all users.</LI><br />
<LI>Users can send private messages to other users.</LI><br />
<LI>Users can create events that represent an actual event in the real world.<br />
Events pull together users, content, and provide basic event management<br />
capabilities, such as RSVP.</LI><br />
<LI>Users can form and join groups. Groups represent a grouping of like-minded<br />
people and pulls together users and content. Groups are permanent.</LI><br />
<LI>Users can comment on various types of shared and created content including<br />
photos, pages, statuses, and activities. Comments are textual only.</LI><br />
<LI>Users can indicate that they like most types of shared and created content<br />
including photos, pages, statuses, and activities.</LI><br />
</UL><br />
<H2>Content sharing</H2><br />
<P>Content sharing features allow users to share content, either self-generated or<br />
discovered, with other users:</P><br />
<UL><br />
<LI>Users can create albums and upload photos to them</LI><br />
<LI>Users can create standalone pages belonging to them or attached pages<br />
belonging to events and groups</LI><br />
</UL><br />
<P>You might notice that some of the features in the previous chapters are similar<br />
to those here. This should not be surprising. Online social networking services<br />
grew from existing communications and community services, often evolving and<br />
incorporating features and capabilities from those services. The approach adopted in<br />
this book is no different. We will be using some of the features we have built in the<br />
previous chapter and adapt them accordingly for Colony.</P><br />
<P><PRE><CODE><br />
	For the observant reader you might notice that the previous<br />
	chapters have clones that end with <I>clone</I>. The original name of this<br />
	clone during writing was <I>Faceclone</I>, but apparently Facebook has<br />
	trademarked <I>Face</I> for many of its applications. In order to avoid<br />
	any potential trademark issues, ichose <I>Colony</I> instead.<br />
</CODE></PRE></P></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/10/cloning-internet-applications-with-ruby/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Introduction to Ruby On Rails</title>
		<link>http://www.javabeat.net/2010/10/introduction-to-ruby-on-rails/</link>
		<comments>http://www.javabeat.net/2010/10/introduction-to-ruby-on-rails/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 01:16:36 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Rails]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=508</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Introduction This article provides an introduction to Ruby on Rails. Ruby is a programming language that is interpreted and Rails is a framework written on top of Ruby for writing Web Applications. The article starts with an introduction to Ruby with respect to the basic syntax usage and provides plenty of samples for illustrating conditional [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h2>Introduction</h2>
<p align="justify">This article provides an introduction to Ruby on Rails. Ruby is a programming language that is interpreted and Rails is a framework written on top of Ruby for writing Web Applications. The article starts with an introduction to Ruby with respect to the basic syntax usage and provides plenty of samples for illustrating conditional constructs and looping constructs. Also the advanced concepts like Classes /Objects and modules will also explained with examples. The later section of the article explains Rails and it starts with the basics of the Model View Controller Architecture for writing Rails application.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/ruby-programming-language-8184044925/p/itmczzj4zffkjhnu?pid=9788184044928&amp;affid=suthukrish" target="_blank">Ruby programming</a></li>
</ul>
<h2>Download Ruby On Rails Sample Code</h2>
<ul>
<li><a href="http://www.javabeat.net/articles/sourcecode/2010/201010-introductiontorubyonrails.zip">Download Ruby On Rails Sample Application</a></li>
</ul>
<h2>Ruby Introduction</h2>
<p align="justify">Ruby is an interpreted language that is easy to use and contains various object oriented features. In this section, we will see the basics of Ruby like variable declaration, conditional constructs, looping, classes/object etc. Readers who are new to ruby can be benefitted with the usage of Ruby in this section.</p>
<h3>Hello Word</h3>
<p align="justify">The following code snippet shows how to declare a variable and store some value in it. It later displays the variable&#8217;s value in the console.</p>
<pre class="brush: java; title: ; notranslate">hello = &quot;Hello World&quot;
puts hello</pre>
<h3>Getting input from user</h3>
<p align="justify">As seen in the last example, the function puts() can be used to output the content to the console and the method gets() is used to obtain the input from the user.</p>
<pre class="brush: java; title: ; notranslate">puts(&quot;Enter a number&quot;);
number = gets();
puts(&quot;The number entered is #{number}&quot;);</pre>
<p align="justify">Also have a look at how the variable&#8217;s value is used within strings. The pattern used will be &#8216;#{variableName}&#8217; when this variable is used within double-quotes.</p>
<h3>Declaring Arrays</h3>
<p align="justify">Ruby supports the declaration of an array through the following syntax. The index of array location starts from zero.</p>
<pre class="brush: java; title: ; notranslate">my_array = [&quot;one&quot;, &quot;two&quot;];
puts my_array[1];
puts &quot;Element at location 0 is #{my_array[0]}&quot;;

puts &quot;Length of the array is is #{my_array.length}&quot;

fruits = Array.new;
fruits[0] = &quot;Apple&quot;;
fruits[1] = &quot;Orange&quot;;
fruits[2] = &quot;Grapes&quot;;

puts &quot;Length of array is #{fruits.length}&quot;</pre>
<p align="justify">The length of the array – which tells the number of elements that an array is holding currently can be determined by calling &#8216;arrayObject.length&#8217;. Another way for declaring a dynamic array is to call &#8216;Array.new&#8217; and the populate the elements with the normal syntax.</p>
<h3>Conditional constructs</h3>
<p align="justify">The following code snippet illustrates the usage of conditional constructs in Ruby. Note the usage of &#8216;if&#8217;, &#8216;elsif&#8217; and &#8216;end&#8217; and the usage of AND operations.</p>
<pre class="brush: java; title: ; notranslate">pizza_price = 80;
if (pizza_price &lt; 100)
  puts &quot;Price is less&quot;;
elsif (pizza_price &gt; 100 &amp;amp;&amp;amp; pizza_price &lt;200)
  puts &quot;Price is medium&quot;;
else
  puts &quot;Price is large&quot;
end</pre>
<p align="justify">The above code displays the price based on various ranges just to illustrate the usage of conditional constructs.</p>
<h3>Looping</h3>
<p align="justify">The usage of &#8216;for&#8217; loop is given below. The code declares a array of programming languages and then iterates over the loop using &#8216;for&#8217; loop.</p>
<pre class="brush: java; title: ; notranslate">languages = [&quot;C&quot;, &quot;C++&quot;, &quot;Java&quot;, &quot;.NET&quot;];

for language in languages
  puts &quot;Language is #{language}&quot;;
end</pre>
<h3>Function</h3>
<p align="justify">Functions are used to define re-usable logic and it can be invoked multiple times. The usage of functions in Ruby is supported through &#8216;def&#8217; keyword followed by the function name.</p>
<pre class="brush: java; title: ; notranslate">def multiply(a, b)
  result = multiply_with_return(a, b);
  puts(&quot;Inside Multiply without return #{result}&quot;);
end

def multiply_with_return(a, b)

  puts(&quot;Multiplying #{a} with #{b}&quot;);
  result = a * b;
  return result;
end

value = multiply_with_return(10, 10);
puts(&quot;Result from multiplying with return is #{value}&quot;);
multiply(5, 3);</pre>
<p align="justify">Functions can support parameters also. In the above code, we have defined functions &#8216;multiply&#8217; and &#8216;multiply_with_return&#8217;. The first function uses the parameters passed by the caller and displays the result within the function definition. The second function, after calculating the result, returns the result to the caller.</p>
<h3>Classes and Objects</h3>
<p align="justify">In this section, we will see the usage of classes and objects in Ruby. As known, class represents the template for creating objects which contains the combination of related operations and data.</p>
<pre class="brush: java; title: ; notranslate">class Arithmetic
  def initialize(a, b)
    @a = a;
    @b = b;
  end

  def add()
    puts(&quot;Addition of #{@a} and #{@b} is #{@a + @b}&quot;);
  end

  def sub()
    puts(&quot;Subtraction of #{@a} and #{@b} is #{@a - @b}&quot;);
  end

  def multiply()
    puts(&quot;Multiplication of #{@a} and #{@b} is #{@a * @b}&quot;);
  end

  def divide()
    puts(&quot;Dividing #{@a} with #{@b} results is #{@a / @b}&quot;);
  end

end

one_two_arithmetic_object = Arithmetic.new(1, 2);
one_two_arithmetic_object.add();
one_two_arithmetic_object.sub();
one_two_arithmetic_object.multiply();
one_two_arithmetic_object.divide();</pre>
<p align="justify">In the above code, we declare a class called &#8216;Arithmetic&#8217; and supports related functions like &#8216;add&#8217;, &#8216;sub&#8217;, &#8216;multiply&#8217; and &#8216;divide&#8217; which does the basic mathematical operations. Callers can create objects for this class and can invoke the various available operations supported by this class. There is a special method available in the class declaration called &#8216;initialize&#8217; which will be invoked automatically when an object is created for this class.<br />
Also note the syntax for creating an object for the class. It is the class name followed by &#8216;new&#8217;. The parameters following the &#8216;new&#8217; keyword are the initialization parameters. Here we have passed the initialization arguments &#8217;1&#8242; and &#8217;2&#8242; and hence the function &#8216;initialize&#8217; will be called with these arguments.</p>
<h3>Modules</h3>
<p align="justify">Modules in ruby are used to group larger number of operations together. In the below example code, we have created two modules called &#8216;Number_Operations&#8217; and &#8216;String_Operations&#8217;. Note that these modules are defined in files &#8216;module_number_operations.rb&#8217; and &#8216;module_string_operations.rb&#8217;.</p>
<pre class="brush: java; title: ; notranslate">module Number_Operations

	def Number_Operations.display()
    puts &quot;Contains the utility operations related to numbers&quot;;
  end

end

module String_Operations

  def String_Operations.display()
    puts &quot;Contains the utility operations related to string&quot;;
  end

end</pre>
<p align="justify">The below code represents the usage of the modules, and for importing the modules within the client applications, the syntax &#8216;require &#8216;, should be used. Then the operations are used through the syntax &#8216;ModuleName.operationName&#8217;.</p>
<pre class="brush: java; title: ; notranslate">require 'module_string_operations'
require 'module_number_operations'

puts String_Operations.display();
puts Number_Operations.display();</pre>
<h2>Rails Framework</h2>
<p align="justify">Ruby is an interpreted programming language and Rails is a framework written on Ruby for building web applications. Rails prefer the approach on convention over configuration which means that when you create a web application using Rails framework, the supporting tools will provide a lot of sensible defaults so that developers can go and hook in only their customizations instead of writing everything from scratch. Also one can see the how faster it will be in developing web applications through Rails when compared with other popular Web application frameworks.</p>
<p align="justify">Rails framework follows the pattern of MVC which stands for Model-View –Controller architecture which is a popular standard/pattern for building web applications. When a client, typically a browser is making a request, it is the Controller which will be handling the request initially. Based on various request parameters, it will identity the type of request and forwards the request to the appropriate Model objects. There can be multiple Model objects that can be maintained in a Web application and it is the Controller&#8217;s responsibility to choose a particular Model object based on various parameters. The Model object represents the action part as well as the data handling part. It may hit the database or can perform any business actions with respect to the context and finally build the data suitable for getting it displayed.</p>
<p align="justify">In this section we will create a Rails starter application that will display some static text in the browser upon client&#8217;s request. Rails come with plentiful of utilities that make the developmental tasks easier. Have a look at the following command which will create a web application. The name of the application is &#8216;hello&#8217; and the &#8216;new&#8217; subcommand indicates that we want to create a new application.</p>
<pre class="brush: java; title: ; notranslate">rails new hello –O</pre>
<p align="justify">Executing the above command will produce an output similar to the following.</p>
<pre class="brush: java; title: ; notranslate">create
      create  README
      create  Rakefile
      create  config.ru
      create  .gitignore
      create  Gemfile
      create  app
      create  app/controllers/application_controller.
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/mailers
      create  app/models
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb
      create  config/environments
      create  config/environments/development.rb
      create  config/environments/production.rb
      create  config/environments/test.rb
      create  config/initializers
      create  config/initializers/backtrace_silencers
      create  config/initializers/inflections.rb
      create  config/initializers/mime_types.rb
      create  config/initializers/secret_token.rb
      create  config/initializers/session_store.rb
      create  config/locales
      create  config/locales/en.yml
      create  config/boot.rb
      create  db
      create  db/seeds.rb
      create  doc
      create  doc/README_FOR_APP
      create  lib
      create  lib/tasks
      create  lib/tasks/.gitkeep
      create  log
      create  log/server.log
      create  log/production.log
      create  log/development.log
      create  log/test.log
      create  public
      create  public/404.html
      create  public/422.html
      create  public/500.html
      create  public/favicon.ico
      create  public/index.html
      create  public/robots.txt
      create  public/images
      create  public/images/rails.png
      create  public/stylesheets
      create  public/stylesheets/.gitkeep
      create  public/javascripts
      create  public/javascripts/application.js
      create  public/javascripts/controls.js
      create  public/javascripts/dragdrop.js
      create  public/javascripts/effects.js
      create  public/javascripts/prototype.js
      create  public/javascripts/rails.js
      create  script
      create  script/rails
      create  test
      create  test/performance/browsing_test.rb
      create  test/test_helper.rb
      create  test/fixtures
      create  test/functional
      create  test/integration
      create  test/unit
      create  tmp
      create  tmp/sessions
      create  tmp/sockets
      create  tmp/cache
      create  tmp/pids
      create  vendor/plugins
      create  vendor/plugins/.gitkeep</pre>
<p align="justify">As you can see, the execution of the command creates a standard directory layout containing lots of files and folders. Since Ruby applications are MVC based, the folders &#8216;app/controllers&#8217;, &#8216;app/models&#8217; and &#8216;app/views&#8217; contain the files related to Controllers, Models and Views respectively. The &#8216;db&#8217; folder contains information related to database for various environments like development, testing and production. The &#8216;configuration&#8217; folder represents the application&#8217;s configuration information such as request-action mapping and other dependencies. Test cases related files come under the &#8216;test&#8217; directory. The &#8216;public&#8217; directory contains the viewable files that can be accessed directly by the client like html, images etc.</p>
<p align="justify">To launch the &#8216;hello&#8217; application, go to the directory &#8216;hello&#8217; (this new directory was created in the previous step) and type the following. Ruby installation comes with a pre-configured web server called &#8216;WEBrick&#8217; and the following command starts the web server in the default port number &#8217;3000&#8242;.</p>
<pre class="brush: java; title: ; notranslate">rails server
=&gt; Booting WEBrick
=&gt; Rails 3.0.0 application starting in development on http://0.0.0.0:3000
=&gt; Call with -d to detach
=&gt; Ctrl-C to shutdown server
[2010-10-09 00:36:29] INFO  WEBrick 1.3.1
[2010-10-09 00:36:29] INFO  ruby 1.9.2 (2010-08-18) [i386-mingw32]
[2010-10-09 00:36:29] INFO  WEBrick::HTTPServer#start: pid=7816 port=3000</pre>
<p align="justify">As soon as the server is started, the application can be accessed through the url &#8216;http://localhost:3000&#8242;. This shows the default page which is located in the folder &#8216;/public/index.html&#8217;. This application really doesn&#8217;t do anything other than creating the basic template for a web application with a default page. Let us add the basic functionality of creating a controller and a view. The controller takes the responsibility of intercepting the client&#8217;s request and it will redirect the control to the view. The view takes the control and the content of the view will be displayed to the browser. The following screen-shot will be displayed when the browser is accessed with the url &#8216;http://localhost:3000&#8242;.</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/10/1.jpg"><img class="aligncenter size-medium wp-image-969" title="1" alt="" src="http://www.javabeat.net/wp-content/uploads/2010/10/1-300x199.jpg" width="300" height="199" /></a></p>
<p align="justify">Execute the following command for creating controller and an action. The &#8216;controller&#8217; subcommand takes the controller name and the action name as arguments. Here the name of the controller is &#8216;hello&#8217; and the name of the action is &#8216;hello_action&#8217;</p>
<pre class="brush: java; title: ; notranslate">rails generate controller hello hello_action
      create  app/controllers/hello_controller.rb
       route  get &quot;hello/hello_action&quot;
      invoke  erb
       exist    app/views/hello
      create    app/views/hello/hello_action.html.erb
      invoke  test_unit
   identical    test/functional/hello_controller_test.rb
      invoke  helper
   identical    app/helpers/hello_helper.rb
      invoke    test_unit
   identical      test/unit/helpers/hello_helper_test.rb</pre>
<p align="justify">The execution of the command creates the controller file &#8216;hello_controller.rb&#8217; in the folder &#8216;/app/controllers&#8217;. Here is the listing for generated &#8216;hello_controller.rb&#8217; file.</p>
<pre class="brush: java; title: ; notranslate">class HelloController &lt; ApplicationController
  def hello_action
  end
end</pre>
<p>In the above code, the &#8216;HelloController&#8217; class inherits from the base controller Application. A controller can have multiple actions and one such action provided is &#8216;hello_action&#8217;. This makes the application to be accessed through this way &#8216;/hello/hello_action&#8217;. We haven&#8217;t provided an implementation for the action and the default implementation is to look for a view file in the directory &#8216;/app/views//.html.erb&#8217;. The generator is sensible enough to create the file &#8216;hello_action.html.erb&#8217; in the folder &#8216;/app/views/hello&#8217;. The content of this view file is given below,</p>
<pre class="brush: java; title: ; notranslate">
&lt;h1&gt;Hello&lt;/h1&gt;
&lt;p&gt;This is a starter application to setup things using Rails framework&lt;/p&gt;
</pre>
<p>This is a starter application to setup things using Rails framework</p>
<p align="justify">Before accessing the application, delete the file &#8216;index.html&#8217; present in the &#8216;/public&#8217; directory, the presence of this file overrides the settings. Now accessing the application through the url &#8216;http://localhost:3000/hello/hello_action&#8217; will display the following view.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/10/2.jpg"><img class="aligncenter size-medium wp-image-970" title="2" alt="" src="http://www.javabeat.net/wp-content/uploads/2010/10/2-300x177.jpg" width="300" height="177" /></a></p>
<p>&nbsp;</p>
<h2>Creating Multiple Controllers/Actions and Views</h2>
<p align="justify">Now that we have a basic understanding on rails, we will extend the above concepts in creating an application that has multiple controllers, actions and views. This sample will illustrate this example by providing the option on displaying the home page of contacts and messages. We will start creating the application by executing the following command,</p>
<pre class="brush: java; title: ; notranslate">rails new lister –O</pre>
<p align="justify">This creates an application called &#8216;lister&#8217;. Change to the directory of &#8216;lister&#8217;. Now we want to create a controller for &#8216;contacts&#8217; which will control the home page display and the listing for all contacts. Execute the following command for creating the controller called &#8216;contacts&#8217;.</p>
<pre class="brush: java; title: ; notranslate">rails generate controller contacts contacts_home contacts_view</pre>
<p align="justify">Other than creating a controller called &#8216;contacts&#8217;, the above command will create two more actions called &#8216;contacts_home&#8217; and &#8216;contacts_view&#8217;. The execution of the above command would result in an output similar to the following.</p>
<pre class="brush: java; title: ; notranslate">create  app/controllers/contacts_controller.rb
      route  get &quot;contacts/contacts_view&quot;
      route  get &quot;contacts/contacts_home&quot;
     invoke  erb
     create    app/views/contacts
     create    app/views/contacts/contacts_home.html.erb
     create    app/views/contacts/contacts_view.html.erb
     invoke  test_unit
     create    test/functional/contacts_controller_test.rb
     invoke  helper
     create    app/helpers/contacts_helper.rb
     invoke    test_unit
     create      test/unit/helpers/contacts_helper_test.rb</pre>
<p align="justify">The definition of the &#8216;contacts_controller&#8217; is shown below. Note that other than the regular controller definitions, two action definitions are added to the file.</p>
<pre class="brush: java; title: ; notranslate">class ContactsController &lt; ApplicationController
  def contacts_home
  end
  def contacts_view
  end
end</pre>
<p align="justify">The action &#8216;contacts_home&#8217; is used to display the home page view for contacts. Here is view definition for &#8216;contacts_home&#8217; found in &#8216;/app/views/contacts/contacts_view.html/erb&#8217;.</p>
<pre class="brush: java; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Contacts Home&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h1&gt;Contacts Home&lt;/h1&gt;
&lt;br&gt;
&lt;br&gt;
&lt;h1&gt;This is the home page for Contacts&lt;/h1&gt;
&lt;br&gt;
&lt;%= link_to &quot;Go to Contacts View.&quot;, :action =&gt; &quot;contacts_view&quot; %&gt;
&lt;br&gt;

&lt;/body&gt;
&lt;/html&gt;
</pre>
<p align="justify">Note that the above view page defines the link to the contacts view and the usage of ruby scriptlets in the above between the symbols &#8216;&lt;#=&#8217; and &#8216;%&gt;&#8217;. A predefined element &#8216;link_to&#8217; is defined containing the action attribute expressed as &#8216;action&#8217;. The display name given to the action is &#8216;Go to Contacts View&#8217;. The action name is given as &#8216;contacts_view&#8217;, note that this action name should match the action name which is defined in the controller. The inclusion of this scriptlet will introduce a link in the html page and by clicking on the link, the user will be redirected to the &#8216;contacts_view&#8217; page.</p>
<p align="justify">Access to the link &#8216;http://localhost:3000/contacts/contacts_home&#8217; will display the following page in the browser.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/10/3.jpg"><img class="aligncenter size-medium wp-image-971" title="3" alt="" src="http://www.javabeat.net/wp-content/uploads/2010/10/3-300x186.jpg" width="300" height="186" /></a></p>
<p align="justify">The code listing for &#8216;contacts_view&#8217; is given below. Note that this view page has some hard-coded contact entries to get them displayed in the browser. Also the view page includes a reference to the contacts home page.</p>
<h2>All Contacts</h2>
<table border="1">
<tbody>
<tr>
<th>Name</th>
<th>Number</th>
</tr>
<tr>
<td>12345</td>
<td>David</td>
</tr>
<tr>
<td>67890</td>
<td>Jones</td>
</tr>
<tr>
<td>13469</td>
<td>Lisa</td>
</tr>
</tbody>
</table>
<pre class="brush: java; title: ; notranslate">
&lt;html&gt;
&lt;head&gt;
&lt;title&gt;Contacts View&lt;/title&gt;
&lt;/head&gt;
&lt;body&gt;
&lt;h2&gt;All Contacts&lt;/h2&gt;

&lt;table border = &quot;1&quot;&gt;
	&lt;tr&gt;
    &lt;th&gt;Name&lt;/th&gt;
    &lt;th&gt;Number&lt;/th&gt;
	&lt;/tr&gt;

  &lt;tr&gt;
    &lt;td&gt;12345&lt;/td&gt;
	&lt;td&gt;David&lt;/td&gt;
  &lt;/tr&gt;

  &lt;tr&gt;
    &lt;td&gt;67890&lt;/td&gt;
	&lt;td&gt;Jones&lt;/td&gt;
  &lt;/tr&gt;
  &lt;tr&gt;
    &lt;td&gt;13469&lt;/td&gt;
	&lt;td&gt;Lisa&lt;/td&gt;
  &lt;/tr&gt;
&lt;/table&gt;
&lt;br&gt;
&lt;%= link_to &quot;Go to Contacts home.&quot;, :action =&gt; &quot;contacts_home&quot; %&gt;
&lt;/body&gt;
&lt;/html&gt;

</pre>
<p align="justify">Access to the link &#8216;http://localhost:3000/contacts/contacts_view&#8217; will display the following page in the browser.</p>
<p><a href="http://www.javabeat.net/wp-content/uploads/2010/10/4.jpg"><img class="aligncenter size-medium wp-image-968" title="4" alt="" src="http://www.javabeat.net/wp-content/uploads/2010/10/4-300x171.jpg" width="300" height="171" /></a></p>
<p align="justify">Execute the following command for creating the controller &#8216;messages&#8217; with two actions &#8216;messages_home&#8217; and &#8216;messages_view&#8217;.</p>
<pre class="brush: java; title: ; notranslate">rails generate controller messages messages_home messages_view</pre>
<p>The source code listing for messages_controller ,&#8217;messages_home&#8217; and &#8216;messages_view&#8217; is not included here and it will look similar to the one that we had already seen before. The URLs for accessing the home page and the listing for messages are &#8216;http://localhost:3000/messages /messages_home&#8217; and &#8216;http://localhost:3000/messages /messages_view&#8217; respectively.</p>
<h2>Conclusion</h2>
<p align="justify">This article provided an introduction to Ruby on Rails explaining the basics in writing Web applications using the Rails framework. Various code samples were discussed to illustrate the basics of Rails framework in writing controllers, actions and views.</p>
<ul>
<li>Buy: <a href="http://www.flipkart.com/ruby-programming-language-8184044925/p/itmczzj4zffkjhnu?pid=9788184044928&amp;affid=suthukrish" target="_blank">Ruby programming</a></li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2010/10/introduction-to-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Develop Ruby on Rails applications fast using RadRails 1.0 Community Edition</title>
		<link>http://www.javabeat.net/2009/11/develop-ruby-on-rails-applications-fast-using-radrails-1-0-community-edition/</link>
		<comments>http://www.javabeat.net/2009/11/develop-ruby-on-rails-applications-fast-using-radrails-1-0-community-edition/#comments</comments>
		<pubDate>Wed, 11 Nov 2009 00:32:18 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=1957</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Aptana RadRails: An IDE for Rails Development Develop Ruby on Rails applications fast using RadRails 1.0 Community Edition Coming from a background of developing in languages such as Java, one of the things that surprised me the most about the Ruby and Rails community, was the common practice of not using an Integrated Development Environment. [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><p><H1><CENTER>Aptana RadRails: An IDE for Rails Development</CENTER></H1><br />
<H1>Develop Ruby on Rails applications fast using RadRails 1.0 Community Edition</H1><br />
<P>Coming from a background of developing in languages such as Java, one of the<br />
things that surprised me the most about the Ruby and Rails community, was the<br />
common practice of not using an Integrated Development Environment. Most of the<br />
members of the community, including the most relevant, were comfortable with just a<br />
programmer&#8217;s editor.</P><br />
<P>At first I thought it was because, Ruby being a dynamic language, using a full IDE might<br />
be an overkill. But then I thought of the PHP community, in which several IDEs are<br />
popular, with PHP also being a dynamic language. So I still had to guess why using an<br />
IDE was not a common practice within the Ruby on Rails world.</P><br />
<P>Nowadays, there is a growing list of IDEs with support for Ruby on Rails, but two<br />
years ago the options were really scarce. Back then, I chose to use RadRails because it<br />
worked on top of the Eclipse IDE—which was the tool I was already using for<br />
other programming languages—and because it was the only free, open source, and<br />
portable option.</P><br />
<P>Truth is, the first version of RadRails I used was very promising, but still a bit too basic.<br />
It featured just a few specialized tools, Ruby syntax colorization, and a slow and faulty<br />
code-assistance. As a result, the difference between RadRails and a good programmer&#8217;s<br />
editor was not really significant. However, as Ruby on Rails gained popularity, RadRails<br />
was vastly improved, and a lot of new features were added.</P><br />
<P>At the same time, several other IDEs started to provide support for Ruby too. Today,<br />
even if many Ruby on Rails developers still don&#8217;t use an IDE, a growing number of<br />
them already.</P><br />
<P>During these two years, I&#8217;ve been developing projects almost exclusively with Ruby on<br />
Rails; and I developed all of them using RadRails. Of course I have been keeping an eye<br />
on every new IDE with Ruby support, just to see if there were any reasons for changing,<br />
but I still didn&#8217;t find any.</P><br />
<P>To me, writing this book is a way of contributing back to the RadRails project. I hope this<br />
book will help the existing community of users of Aptana RadRails, and will also help<br />
new users to start working with this tool. Besides, thanks to the Packt Open Source<br />
Project Royalty Scheme, a part of the benefits will be directly paid as a royalty to the<br />
RadRails project, so by purchasing this book you are funding a bit of the Community<br />
Edition of Aptana RadRails.</P><br />
<H1>What This Book Covers</H1><br />
<P>This book will show you how to get the most of the Community Edition of Aptana<br />
RadRails for developing Ruby on Rails projects. Apart from the features provided by<br />
RadRails, the book will give you an overview of working with the Eclipse IDE,<br />
and will show you how to use the Eclipse functionalities that are relevant for Ruby and<br />
Rails development.</P><br />
<P>This book is not about the Ruby programming language or the Ruby on Rails framework.<br />
Even if you don&#8217;t need to be an expert, you should already be familiar with the language<br />
and the framework to get the most from this book.</P><br />
<P>Chapters 1 and 2 will show you how to install and configure Aptana RadRails, and will<br />
help you find your way around the Eclipse IDE. If you have previous experience with<br />
Eclipse , and you have already installed Aptana RadRails, then you can proceed directly<br />
to Chapter 3.</P><br />
<P>Chapters 3 to 8 are a complete reference to each of the components of RadRails,<br />
including all the configuration options.</P><br />
<P>Finally, in Chapter 9 you will find documentation about some complementary plugins<br />
you can use for connecting to a database and for managing your source repositories.</P><br />
<P>You can find below a brief introduction to each of the chapters.</P><br />
<P><I>Chapter 1</I>: This chapter will introduce you the concept of IDE and will give you a<br />
general overview of what you can expect from Aptana RadRails. You will also find<br />
instructions about how to install Aptana RadRails and the Eclipse IDE in your system.<br />
Even if you should already be familiar with the installation of Ruby and Rails, the chapter<br />
also provides a quick reference for installing Ruby and Ruby on Rails on Windows,<br />
Linux, and OSX.</P><br />
<P><I>Chapter 2</I>: In most cases, Aptana RadRails will work directly out of the box. However, in<br />
some cases you will need to make a minimal configuration of the IDE. The first part of<br />
this chapter will show you the basic configuration of RadRails.</P><br />
<P><I>Chapter 3</I>: Two of the basic tools RadRails provides are the Ruby Explorer and the<br />
Console View. With the Ruby explorer you will be able to browse the structure of your<br />
projects and perform any kind of file-related operations, including working with the local<br />
history of your files. The console view will display the output of most of the processes<br />
we will launch from RadRails. Apart from learning how to use these views, we will show<br />
how to use Generators and Rake Tasks from Aptana RadRails to create a simple demo<br />
application. You will also learn how to start and stop your servers and how to use the<br />
built-in browser to watch your application in action.</P><br />
<P><I>Chapter 4</I> explains in detail all the built-in capabilities of RadRails for developing Ruby<br />
code. You will learn to use the Ruby Editor to write your source code, to navigate<br />
between the different classes and files, and to get the most out of code completion and the<br />
code templates.</P><br />
<P><I>Chapter 5</I>: One of the strong points of Aptana RadRails is the great support for the clientside<br />
of your application: JavaScript, HTML, and CSS. In this chapter you will learn how<br />
to write Rails views mixing together Ruby code with HTML or JavaScript and getting<br />
assistance for all of the languages.</P><br />
<P><I>Chapter 6</I>: When an application grows large, it&#8217;s always a good idea to have a way of<br />
debugging the potential errors. This chapter will show you how to use RadRails&#8217; built-in<br />
debugger for interacting with your code at run time. You will learn to start a server or a<br />
stand-alone script in debug mode, how to set breakpoints , and how to intercept any Ruby<br />
exceptions. The debugger will also allow you to walk through your code, to examine the<br />
values of any variables and expressions, and even to execute arbitrary code at run time by<br />
using the Display view.</P><br />
<P><I>Chapter 7</I>: Apart from the coding and debugging, Aptana RadRails provides a number of<br />
specialized tools to make the development and management of your application easier. In<br />
the context of Eclipse, each of these tools is called a View. In this chapter, you will learn<br />
how to use the different views to browse the Ruby and Rails documentation, manage and<br />
monitor your servers, install gems and plugins, launch generators and rake tasks, use code<br />
annotations, keep track of warnings and to-do lists, evaluate regular expressions, and run<br />
your tests. If you prefer to use the command line, then you will learn how to take<br />
advantage of the built-in Rails Shell, in which you can get auto-completion for the most<br />
used Ruby and Rails commands directly at the command line. This chapter will also<br />
show you how to use your IDE to control external servers such as Apache or MySQL.</P><br />
<P><I>Chapter 8</I>: Out of the box, Aptana RadRails provides a fully working environment.<br />
However, many of its components allow for some configuration. This chapter is a<br />
complete reference to all the preferences you can set to change the user experience when<br />
using RadRails.</P><br />
<P><I>Chapter 9</I>: Aptana RadRails bundles together plenty of interesting features for the<br />
developer. However, since the focus is on Ruby on Rails, there are some general aspects<br />
of the development of a project that are not covered by RadRails. Fortunately, since the<br />
underlying platform is the Eclipse IDE, we have a virtually unlimited number of<br />
complementary plugins to choose from. This chapter will give you a general overview of<br />
the Eclipse plugins ecosystem, and will also explain in detail how to use two of the<br />
plugins you might want to use when developing. DBViewer is a plugin you can use to<br />
connect to your database from the IDE. This chapter will show you how to set up the<br />
plugin, and how to use it for examining and modifying your database structure and<br />
contents. Subclipse is a plugin to connect to Subversion repositories. By using Subclipse<br />
you will have repository access directly from your IDE. Besides, the built-in features of<br />
Subclipse will help you examine and merge changes in a much more comfortable way<br />
than using the Subversion command line.</P><br />
<H1><CENTER>RadRails Views</CENTER></H1><br />
<P>By now you should be comfortable with the general interface of Eclipse and<br />
RadRails. You know already how to create Rails projects, write and debug Ruby code<br />
and views, and work with HTML, JavaScript, and CSS files. We could say most of<br />
our programming needs are fulfilled with that.</P><br />
<P>When developing a Rails project, there are more things to do than the source code<br />
itself. We have to start, stop, and monitor our servers, generate code templates, run<br />
our test suites, install plugins and gems, generate documentation, keep control<br />
of to-do items, or run Rake tasks for different purposes—database migrations,<br />
for example.</P><br />
<P>RadRails provides different views for supporting these tasks that are a part of<br />
the development but not of the coding itself. And, of course, it does it so we can<br />
control everything from within the IDE without having to go back to the<br />
command-line interface.</P><br />
<P>We already had a glimpse of some of these features when using the Generators,<br />
Rake, or Servers views briefl y when we needed them in previous chapters. Now you<br />
will learn how to take full advantage of all the RadRails views, to help you take care<br />
of routine processes and just focus on getting things done.</P><br />
<H1>Opening the RadRails Views</H1><br />
<P>Some of the views that we will go through in this chapter are available as part of<br />
the Rails default perspective, which means you don&#8217;t need to do anything special<br />
to open them; they will appear as tabbed views in a pane at the bottom of your<br />
workbench. Just look for the tab name of the view you want to see and click on it to<br />
make it visible.</P><br />
<P>However, there are some views that are not opened by default, or maybe you closed<br />
them at some point accidentally, or maybe you changed to the Debug perspective<br />
and you want to display some of the RadRails views there. When you need to open<br />
a view whose tab is not displaying, you can go to the <B>Window</B> menu, and select the<br />
<B>Show View</B> option.</P></p>
<p><center><img src="images/2009/12/RadRails/1.jpg"/></center></p>
<p><P>If you are in the Rails perspective, all the available views will be displayed in that<br />
menu, as you can see in the screenshot above. When opening this menu from a<br />
different perspective, you will not see the RadRails views here, but you can select<br />
<B>Other&#8230;</B> as we did in previous chapters. If this is the case, in the <B>Show View</B> dialog,<br />
most of the views will appear under the <B>Ruby</B> category, except for the <B>Generators</B>,<br />
<B>Rails API</B>, and <B>Rake Tasks</B> views, which are located under <B>Rails</B>.</P><br />
<H1>Documentation Views</H1><br />
<P>As happens with any modern programming language, Ruby has an extensive<br />
API. There are lots of libraries and classes and even with Ruby being an intuitive<br />
language with a neat consistent API, often we need to read the documentation.</P><br />
<P>As you probably know, Ruby provides a standard documentation format called<br />
RDoc, which uses the comments in the source code to generate documentation. We<br />
can access this RDoc documentation in different ways, mainly in HTML format<br />
through a browser or by using the command-line tool RI. This produces a plain-text<br />
output directly at the command shell, in a similar way to the man command in a<br />
UNIX system.</P><br />
<P>RadRails doesn&#8217;t add any new functionalities to the built-in documentation, but<br />
provides some convenient views so we can explore it without losing the context of<br />
our project&#8217;s source.</P><br />
<H1>Ruby Interactive (RI) View</H1><br />
<P>This view provides a fast and comfortable way of browsing the local documentation<br />
in the same way as you would use RI from the command line.</P></p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<p><center><img src="images/2009/12/RadRails/2.jpg"/></center></p>
<p><P>You can look either for a class or a method name. Just start typing at the input box<br />
at the top left corner of the view and the list below will display the matching entries.<br />
That&#8217;s a nice improvement over the command line interface, since you can see the<br />
results as you type instead of having to run a complete search every time.</P><br />
<P>If you know the name of both the class and the method you are looking for, then<br />
you can write them using the hash (pound) sign as a separator. For example, to get<br />
the documentation for the <B>sum</B> method of the class <B>Enumerable</B> you would write<br />
<B>Enumerable#sum</B>.</P><br />
<P>The documentation will display in the right pane, with a convenient highlighting of<br />
the referenced methods and classes. Even if the search results of RI don&#8217;t look very<br />
attractive compared to the output of the HTML-based documentation views, RI has<br />
the advantage of searching locally on your computer, so you can use it even when<br />
working off-line.</P></p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/11/develop-ruby-on-rails-applications-fast-using-radrails-1-0-community-edition/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Ruby on Rails Web Mashup Projects</title>
		<link>http://www.javabeat.net/2009/10/ruby-on-rails-web-mashup-projects/</link>
		<comments>http://www.javabeat.net/2009/10/ruby-on-rails-web-mashup-projects/#comments</comments>
		<pubDate>Tue, 06 Oct 2009 14:15:57 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2009</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Ruby on Rails Web Mashup Projects A step-by-step tutorial to building web mashups A web mashup is a new type of web application that uses data and services from one or more external sources to build entirely new and different web applications. Web mashups usually mash up data and services that are available on the [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1><center>Ruby on Rails Web Mashup Projects</center></h1>
<h1>A step-by-step tutorial to building web mashups</h1>
<p>A web mashup is a new type of web application that uses data and services from one or<br />
more external sources to build entirely new and different web applications. Web mashups<br />
usually mash up data and services that are available on the Internet—freely,<br />
commercially, or through other partnership agreements. The external sources that a<br />
mashup uses are known as mashup APIs.</p>
<p>This book shows you how to write web mashups using Ruby on Rails—the new web<br />
application development framework. The book has seven real-world projects—the format<br />
of each project is similar, with a statement of the project, discussion of the main protocols<br />
involved, an overview of the API, and then complete code for building the project. You<br />
will be led methodically through concrete steps to build the mashup, with asides to<br />
explain the theory behind the code.</p>
<h1>What This Book Covers</h1>
<p>The first chapter introduces the concepts of web mashups to the reader and provides a<br />
general introduction to the benefits and pitfalls of using web mashups as standalone<br />
applications or as part of existing web applications.</p>
<p>The first project is a mashup plugin into an existing web application that allows users to<br />
find the location of the closest facility from a particular geographic location based on a<br />
specified search radius. The location is mapped and displayed on Google Maps.</p>
<p>The second project is another mashup plugin. This plugin allows users to send messages<br />
to their own list of recipients, people who are previously unknown to the website, on<br />
behalf of the website. The project uses Google Spreadsheets and EditGrid to<br />
aggregate the information, and Clickatell and Interfax to send SMS messages and<br />
faxes respectively.</p>
<p>The third project describes a mashup plugin that allows you to track the sales ranking and<br />
customer reviews of a particular product from Amazon.com. The main API used is the<br />
Amazon E-Commerce Service (ECS).</p>
<p>The fourth project shows you how to create a full-fl edged Facebook application that<br />
allows a user to perform some of the functions and features of a job board. This mashup<br />
uses Facebook, Google Maps, Daylife, Technorati and Indeed.com APIs.</p>
<p>The fifth project shows you how to create a full web mashup application that allows users<br />
to view information on a location. This is the chapter that uses the most mashup APIs,<br />
including Google Maps, FUTEF, WebserviceX, Yahoo! Geocoding services,<br />
WeatherBug, Kayak, GeoNames, Flickr, and Hostip.info.</p>
<p>The sixth project describes a mashup plugin that allows an online event ticketing<br />
application to receive payment through Paypal, send SMS receipts, and add event records<br />
in the customer&#8217;s Google Calendar account. The APIs used are Google Calendar, PayPal,<br />
and Clickatell.</p>
<p>The final project shows a complex mashup plugin used for making corporate expense<br />
claims. It allows an employee to submit expense claims in Google Docs and<br />
Spreadsheets, attaching the claims form and the supporting receipts. His or her manager,<br />
also using Google Docs and Spreadsheets, then approves the expense claims and the<br />
approved claims are retrieved by the mashup and used to reimburse the employee through<br />
PayPal. It uses the PayPal APIs and various Google APIs.</p>
<h1><center>&#8216;Find closest&#8217; mashup plugin</center></h1>
<h2>What does it do?</h2>
<p>This mashup plugin allows your Rails website or application to have an additional<br />
feature that allows your users to find the location of the closest facility from a<br />
particular geographic location based on a specified search radius. This mashup<br />
plugin integrates with your existing website that has a database of locations of<br />
the facilities.</p>
<h2>Building a kiosk locator feature for your site</h2>
<p>Your company has just deployed 500 multi-purpose payment kiosks around the<br />
country, cash cows for the milking. Another 500 more are on the way, promising to<br />
bring in the big bucks for all the hardworking employees in the company. Naturally<br />
your boss wants as many people as possible to know about them and use them.<br />
The problem is that while the marketing machine churns away on the marvels and<br />
benefits of the kiosks, the customers need to know where they are located to use<br />
them. He commands you:</p>
<p>
<pre><code><i>
	"Find a way to show our users where the nearest kiosks to him are, and directions
	to reach them!"
</i></code></pre>
</p>
<p>What you have is a database of all the 500 locations where the kiosks are located, by<br />
their full address. What can you do?</p>
<h2>Requirements overview</h2>
<p>Quickly gathering your wits, you penned down the following quick requirements:</p>
<ol>
<li>Each customer who comes to your site needs to be able to find the closest<br />
kiosk to his or her current location.</li>
<li>He or she might also want to know the closest kiosk to any location.</li>
<li>You want to let the users determine the radius of the search.</li>
<li>Finding the locations of the closest kiosks, you need to show him how to<br />
reach them.</li>
<li>You have 500 kiosks now, (and you need to show where they are) but<br />
another 500 will be coming, in 10s and 20s, so the location of the kiosks need<br />
to be specified during the entry of the kiosks. You want to put all of these on<br />
some kind of map.</li>
</ol>
<p>Sounds difficult? Only if you didn&#8217;t know about web mashups!</p>
<h2>Design</h2>
<p>The design for this first project is rather simple. We will build a simple database<br />
application using Rails and create a main Kiosk class in which to store the kiosk<br />
information including its address, longitude, and latitude information. After<br />
populating the database with the kiosk information and address, we will use a<br />
geolocation service to discover its longitude and latitude. We store the information in<br />
the same table. Next, we will take the kiosk information and mash it up with Google<br />
Maps and display the kiosks as pushpins on the online map and place its information<br />
inside an info box attached to each pushpin.</p>
<h2>Mashup APIs on the menu</h2>
<p>In this chapter we will be using the following services to create a &#8216;find closest&#8217;<br />
mashup plugin:</p>
<ul>
<li>Google Maps APIs including geocoding services</li>
<li>Yahoo geocoding services (part of Yahoo Maps APIs)</li>
<li>Geocoder.us geocoding services</li>
<li>Geocoder.ca geocoding services</li>
<li>Hostip.info</li>
</ul>
<h3>Google Maps</h3>
<p>Google Maps is a free web-based mapping service provided by Google. It provides<br />
a map that can be navigated by dragging the mouse across it and zoomed in and out<br />
using the mouse wheel or a zoom bar. It has three forms of views—map, satellite and<br />
a hybrid of map and satellite. Google Maps is coded almost entirely in JavaScript and<br />
XML and Google provides a free JavaScript API library that allows developers to<br />
integrate Google Maps into their own applications. Google Maps APIs also provide<br />
geocoding capabilities, that is, they able to convert addresses to longitude and<br />
latitude coordinates.</p>
<p>We will be using two parts of Google Maps:</p>
<ul>
<li>Firstly to geocode addresses as part of GeoKit&#8217;s APIs</li>
<li>Secondly to display the found kiosk on a customized Google Maps map</li>
</ul>
<h3>Yahoo Maps</h3>
<p>Yahoo Maps is a free mapping service provided by Yahoo. Much like Google Maps it<br />
also provides a map that is navigable in a similar way and also provides an extensive<br />
set of APIs. Yahoo&#8217;s mapping APIs range from simply including the map directly<br />
from the Yahoo Maps website, to Flash APIs and JavaScript APIs. Yahoo Maps also<br />
provides geocoding services. We will be using Yahoo Maps geocoding services as<br />
part of GeoKit&#8217;s API to geocode addresses.</p>
<h3>Geocoder.us</h3>
<p>Geocoder.us is a website that provides free geocoding of addresses and intersections<br />
in the United States. It relies on Geo::Coder::US, a Perl module available for<br />
download from the CPAN and derives its data from the TIGER/Line data set,<br />
public-domain data from the US Census Bureau. Its reliability is higher in urban<br />
areas but lower in the other parts of the country. We will be using Geocoder.us as<br />
part of GeoKit&#8217;s API to geocode addresses.</p>
<h3>Geocoder.ca</h3>
<p>Geocoder.ca is a website that provides free geocoding of addresses in the United<br />
States and Canada. Like Geocoder.us. it uses data from TIGER/Line but in addition,<br />
draws data from GeoBase, the Canadian government-related initiative that provides<br />
geospatial information on Canadian territories. We will be using Geocoder.ca as part<br />
of GeoKit&#8217;s API to geocode addresses.</p>
<h3>Hostip.info</h3>
<p>Hostip.info is a website that provides free geocoding of IP addresses. Hostip.info<br />
offers an HTTP-based API as well as its entire database for integration at no cost. We<br />
will be using Hostip.info as part of GeoKit&#8217;s API to geocode IP addresses.</p>
<h2>GeoKit</h2>
<p>GeoKit is a Rails plugin that enables you to build location-based applications. For<br />
this chapter we will be using GeoKit for its geocoding capabilities in two ways:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li>To determine the longitude and latitude coordinates of the kiosk from its<br />
given address</li>
<li>To determine the longitude and latitude coordinates of the user from his or<br />
her IP address</li>
</ul>
<p>GeoKit is a plugin to your Rails application so installing it means more or less<br />
copying the source files from the GeoKit Subversion repository and running<br />
through an installation script that adds certain default parameters in your<br />
environment.rb file.</p>
<p>To install the GeoKit, go to your Rails application folder and execute this at the<br />
command line:</p>
<p>
<pre><code><b>
$./script/plugin install svn://rubyforge.org/var/svn/geokit/trunk
</b></code></pre>
</p>
<p>This will copy the necessary files to your RAILS_ROOT/vendor/plugins folder and<br />
run the install.rb script.</p>
<p><center><img src="images/2009/10/Mashup-Plugin/1.GIF"/></center></p>
<h3>Configuring GeoKit</h3>
<p>After installing GeoKit you will need to configure it properly to allow it to work.<br />
GeoKit allows you to use a few sets of geocoding APIs, including Yahoo, Google,<br />
Geocoder.us, and Geocoder.ca.</p>
<p>These geocoding providers can be used directly or through a cascading failover<br />
sequence. Using Yahoo or Google requires you to register for an API key but they are<br />
free. Geocoder.us is also free under certain terms and conditions but both Geocoder.us<br />
and Geocoder.ca have commercial accounts. In this chapter I will briefl y go through<br />
how to get an application ID from Yahoo and a Google Maps API key from Google.</p>
<h3>Getting an application ID from Yahoo</h3>
<p>Yahoo&#8217;s application ID is needed for any Yahoo web service API calls. You can<br />
use the same application ID for all services in the same application or multiple<br />
applications or one application ID per service.</p>
<p>To get the Yahoo application ID, go to https://developer.yahoo.com/wsregapp/<br />
index.php and provide the necessary information. Note that for this application<br />
you don&#8217;t need user authentication. Once you click on submit, you will be provided<br />
an application ID.</p>
<h3>Getting a Google Maps API key from Google</h3>
<p>To use Google Maps you will need to have a Google Maps API key. Go to<br />
http://www.google.com/apis/maps/signup.html. After reading the terms and<br />
conditions you will be asked to give a website URL that will use the Google<br />
Maps API.</p>
<p>For geocoding purposes, this is not important (anything will do) but to display<br />
Google Maps on a website, this is important because Google Maps will not display if<br />
the URL doesn&#8217;t match. However all is not lost if you have provided the wrong URL<br />
at first; you can create any number of API keys from Google.</p>
<h3>Configuring evironment.rb</h3>
<p>Now that you have a Yahoo application ID and a Google Maps API key, go to<br />
environment.rb under the RAILS_ROOT/config folder. Installing GeoKit should<br />
have added the following to your environment.rb file:</p>
<p>
<pre><code>
	# Include your application configuration below
	# These defaults are
	used in GeoKit::Mappable.distance_to and in acts_as_mappable
	GeoKit::default_units = :miles
	GeoKit::default_formula = :sphere
	# This is the timeout value in seconds to be used for calls to the
	geocoder web
	# services. For no timeout at all, comment out the setting. The
	timeout unit is in seconds.
	# GeoKit::Geocoders::timeout = 3
	# These settings are used if web service calls must be routed through
	a proxy.
	# These setting can be nil if not needed, otherwise, addr and port
	must be filled in at a minimum. If the proxy requires authentication,
	the username and password can be provided as well.
	GeoKit::Geocoders::proxy_addr = nil
	GeoKit::Geocoders::proxy_port = nil
	GeoKit::Geocoders::proxy_user = nil
	GeoKit::Geocoders::proxy_pass = nil
	# This is your yahoo application key for the Yahoo Geocoder
	# See http://developer.yahoo.com/faq/index.html#appid and

http://developer.yahoo.com/maps/rest/V1/geocode.html

	<b>GeoKit::Geocoders::yahoo = &lt;YOUR YAHOO APP ID&gt;</b>
	# This is your Google Maps geocoder key.
	# See http://www.google.com/apis/maps/signup.html and

http://www.google.com/apis/maps/documentation/#Geocoding_Examples

	<b>GeoKit::Geocoders::google = &lt;YOUR GOOGLE MAPS KEY&gt;</b>
	# This is your username and password for geocoder.us
	# To use the free service, the value can be set to nil or false. For
	usage tied to an account, the value should be set to
	username:password.
	# See http://geocoder.us and

http://geocoder.us/user/signup

	GeoKit::Geocoders::geocoder_us = false
	# This is your authorization key for geocoder.ca.
	# To use the free service, the value can be set to nil or false. For
	usage tied to an account, set the value to the key obtained from
	Geocoder.ca
	# See http://geocoder.ca and

http://geocoder.ca/?register=1

	GeoKit::Geocoders::geocoder_ca = false
	# This is the order in which the geocoders are called in a failover
	scenario
	# If you only want to use a single geocoder, put a single symbol in
	the array.
	# Valid symbols are :google, :yahoo, :us, and :ca
	# Be aware that there are Terms of Use restrictions on how you can
	use the various geocoders. Make sure you read up on relevant Terms of
	Use for each geocoder you are going to use.
	<b>GeoKit::Geocoders::provider_order = [:google,:yahoo]</b>
</code></pre>
</p>
<p>Go to the lines where you are asked to put in the Yahoo and Google keys and change<br />
the values accordingly. Make sure the keys are within apostrophes.</p>
<p>Then go to the provider order and put in the order you want (the first will be tried; if<br />
that fails it will go to the next until all are exhausted):</p>
<p>
<pre><code>
	GeoKit::Geocoders::provider_order = [:google,:yahoo]
</code></pre>
</p>
<p>This completes the configuration of GeoKit.</p>
<h2>YM4R/GM</h2>
<p>YM4R/GM is another Rails plugin, one that facilitates the use of Google Maps APIs.<br />
We will be using YM4R/GM to display the kiosk locations on a customized Google<br />
Map. This API essentially wraps around the Google Maps APIs but also provides<br />
additional features to make it easier to use from Ruby. To install it, go to your Rails<br />
application folder and execute this at the command line:</p>
<p>
<pre><code><b>
$./script/plugin install svn://rubyforge.org/var/svn/ym4r/Plugins/GM/
trunk/ym4r_gm
</b></code></pre>
</p>
<p>During the installation, the JavaScript files found in the RAILS_ROOT/vendors/<br />
plugin/javascript folder will be copied to the RAILS_ROOT/public/javascripts<br />
folder.</p>
<p>A gmaps_api_key.yml file is also created in the RAILS_ROOT/config folder. This file<br />
is a YAML representation of a hash, like the database.yml file in which you can set<br />
up a test, development, and production environment. This is where you will put<br />
in your Google Maps API key (in addition to the environment.rb you have<br />
changed earlier).</p>
<p>For your local testing you will not need to change the values but once you deploy<br />
this in production on an Internet site you will need to put in a real value according to<br />
your domain.</p>
<h3>What we will be doing</h3>
<p>As this project is a mashup plugin, normally you would already have an existing<br />
Rails application you want to add this to. However for the purpose of this chapter, I<br />
show how the mashup can be created on a fresh project. This is what we will<br />
be doing:</p>
<ul>
<li>Create a new Rails project</li>
<li>Install the Rails plugins (GeoKit and YM4R/GM) that will use the<br />
various mashup APIs</li>
<li>Configure the database access and create the database</li>
<li>Create the standard scaffolding</li>
<li>Populate the longitude and latitude of the kiosks</li>
<li>Create the find feature</li>
<li>Display the found kiosk locations on Google Maps</li>
</ul>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/10/ruby-on-rails-web-mashup-projects/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Building Dynamic Web 2.0 Websites with Ruby on Rails</title>
		<link>http://www.javabeat.net/2009/09/building-dynamic-web-2-0-websites-with-ruby-on-rails/</link>
		<comments>http://www.javabeat.net/2009/09/building-dynamic-web-2-0-websites-with-ruby-on-rails/#comments</comments>
		<pubDate>Tue, 29 Sep 2009 14:28:51 +0000</pubDate>
		<dc:creator>krishnas</dc:creator>
				<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://www.javabeat.net/?p=2064</guid>
		<description><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><p>Building Dynamic Web 2.0 Websites with Ruby on Rails Ruby on Rails is an open-source web application framework ideally suited to building business applications, accelerating and simplifying the creation of database-driven websites. It has been developed on the Ruby platform. This book is a tutorial for creating a complete website with Ruby on Rails (RoR). [...]</p>]]></description>
				<content:encoded><![CDATA[<p>Connect to us ( <a href="https://twitter.com/javabeat">@twitter</a> | <a href="https://www.facebook.com/javabeat.net">@facebook )</p><div class="wpInsert wpInsertInPostAd wpInsertLeft" style="float: left; margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Rect */
google_ad_slot = "9976259118";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div><h1><center>Building Dynamic Web 2.0 Websites with Ruby on Rails</center></h1>
<p>Ruby on Rails is an open-source web application framework ideally suited to<br />
building business applications, accelerating and simplifying the creation of<br />
database-driven websites. It has been developed on the Ruby platform.</p>
<p>This book is a tutorial for creating a complete website with Ruby on Rails (RoR).<br />
It will teach you to develop database-backed web applications according to the<br />
Model-View-Controller pattern. It will take you on a joy ride right from installation<br />
to a complete dynamic website. All the applications discussed in this book will<br />
help you add exciting features to your website. This book will show you how to<br />
assemble RoR&#8217;s features and leverage its power to design, develop, and deploy<br />
a fully featured website.</p>
<h1><center>What This Book Covers</center></h1>
<p><i>Chapter 1</i> gives you an overview of the features of Ruby and RoR, as well as<br />
providing the various ways of installing, configuring, and testing both Ruby and<br />
RoR.</p>
<p><i>Chapter 2</i> introduces you to the basics of Ruby as well as the main concepts<br />
and components of RoR.</p>
<p><i>Chapter 3</i> makes you understand the design of tables according to the<br />
conventions of RoR, creation of scaffolds for tables, and changing the scaffolds<br />
according to the requirements.</p>
<p><i>Chapter 4</i> gives you details about how to set up the User Management module<br />
for the website called TaleWiki.</p>
<p><i>Chapter 5</i> makes you familiar with the Login Management and Comment<br />
Management modules for TaleWiki.</p>
<p><i>Chapter 6</i> introduces you to the Migrations and Layouts involved in setting up<br />
the template for TaleWiki.</p>
<p><i>Chapter 7</i> describes the tagging functionality being implemented for the<br />
enhanced search usability.</p>
<p><i>Chapter 8</i> provides you with the implementation of AJAX for TaleWiki.</p>
<p><i>Chapter 9</i> deals with the development of an interface for the administration.</p>
<p><i>Chapter 10</i> gives you the steps for deploying the website.</p>
<h1><center>Gathering User Comments</center></h1>
<p>In the last chapter, we saw how to set up User Management and Role Management<br />
for TaleWiki. However, we did not set up the Login Management based on Users.<br />
So, it was work only half done. To complete the task, we will set up Login<br />
Management in this chapter. It will not only authenticate a user but also provide<br />
the session management.</p>
<p>Secondly, we will look at how to gather user comments for a particular story. We<br />
will start with the functionalities to be provided by the Comment Gathering module.<br />
We will then move on to the database design for the module. After that we will not<br />
only set up the Login Management but also modify the Tale Management so that<br />
the User and Tales can be related. We will wrap up with the implementation of the<br />
Comment Gathering module. Let&#8217;s gets started.</p>
<h1>Understanding the Requirements</h1>
<p>In this chapter, we will be tackling two problems—managing the user authentication<br />
as well as the session management and accepting comments from other users for a<br />
particular tale. So we can divide the requirements into two:</p>
<ul>
<li>Login Management</li>
<li>Comment management</li>
</ul>
<p>The Login Management module will also provide the solution to the problem of Tale<br />
management that evolved during the development of User management. As the tales<br />
table refers to the users table, without a user id a new tale cannot be submitted. The<br />
Login management will provide us the user id corresponding to the new tales. Also,<br />
it will tell us who has commented on a particular tale. Let us see how.</p>
<h2>Login Management</h2>
<p>As the name suggests, the main functionality the Login Management will provide<br />
will be managing the logins. However, managing logins is not a single task. It is<br />
dependent on others tasks or operations as well. So, the overall functionalities we<br />
will be developing as part of Login management are:</p>
<ul>
<li><b>Authenticating the User:</b> We can allow only the registered users to access<br />
the functionalities of TaleWiki. This operation will ensure that the user is a<br />
registered user before he or she tries to enter the TaleWiki.</li>
<li><b>Setting the Session:</b> Once the user is found to be authentic, then we have<br />
to <i>maintain his/her authenticity</i> until he/she logs out. The authenticity can be<br />
maintained by this functionality.</li>
<li><b>Checking Roles:</b> Each User is assigned a Role. So we will need to check<br />
whether a particular functionality—such as viewing details of another<br />
user—is a part of the Role. This functionality will check the User&#8217;s Role<br />
whenever he/she tries to access any functionality provided by TaleWiki.</li>
<li><b>Invalidating Session:</b> When a user logs out, all the details of the user in the<br />
current session need to be cleared out. This functionality will clear out all the<br />
details of the user, including whether the user is authentic or not.</li>
</ul>
<p>Now that we have defined the functionalities of Login management, let us move on<br />
to the next set of tasks—managing the comments.</p>
<h2>Managing the Comments</h2>
<p>It is natural for a person to comment upon whatever he or she reads. So, it is<br />
necessary to provide a way for users to comment on a particular story. The<br />
comments can be of two types—<i>threaded</i> and <i>non-threaded</i>. In <i>threaded</i> comments, one<br />
comment can be posted as a response for another comment. If the first comment is<br />
removed, then all its child comments will also be removed. If we go for <i>non-threaded</i><br />
comments, then each comment is considered an individual. So if one is deleted,<br />
others are not affected.</p>
<p>The Comment Management module will do the same. The functionalities that the<br />
Comment Management module will provide are:</p><div class="wpInsert wpInsertInPostAd wpInsertMiddle" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* Article-Middle-Med-Rect */
google_ad_slot = "7805667846";
google_ad_width = 300;
google_ad_height = 250;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>
<ul>
<li><b>Adding a Comment:</b> When a user wants to comment on a particular story,<br />
he or she can use this functionality. A user can comment on many stories.<br />
Comments are not <i>threaded</i>. That means a comment cannot be a response for<br />
another comment. Each comment is considered an individual.</li>
<li><b>Deleting a Comment:</b> If an administrator finds a comment offensive or feels<br />
that comments are very old, this functionality can be used to delete such<br />
comments. Only the administrator will have access to this functionality.</li>
<li><b>Viewing Comments:</b> Using this functionality, a user can read all the comments<br />
submitted for a particular story. It will be available for all users. In addition,<br />
the comments will be shown in the list view and the <i>details</i> view. In list view,<br />
the comments will be shown for each story, and in the details view, all the<br />
details including the date and complete text of the comment will be shown.</li>
</ul>
<p>We are not providing a way to modify a posted comment. That is because comments<br />
are considered one time and brief view of what the user thinks. Hence, no<br />
functionality will be provided for the modification of comments. That wraps up the<br />
requirements of the Login and Comment Management modules. Next, let us work<br />
on the database design for the modules.</p>
<h1>Designing the Database</h1>
<p>As you would have already guessed, our next step will be designing the database.<br />
However, unlike the modules that we developed previously, we will be designing<br />
the database only for one of the two modules. The Login management module<br />
doesn&#8217;t require a table because its functionalities are based on the users and roles<br />
tables. So we will have to design the table for the Comment management module<br />
only. Just like the previous chapter, the steps for designing the database are:</p>
<ul>
<li>Designing the E-R Model</li>
<li>Deriving the Schemas</li>
<li>Creating the Tables</li>
</ul>
<p>Whenever a new module is added, some of the existing E-R models need to be<br />
refined, and consequently the corresponding schemas and tables will be changed<br />
accordingly. In the case of Comment management, this holds true as you will see as<br />
we go through the steps. So here we go.</p>
<h2>Designing the E-R Model</h2>
<p>As the name suggests, the Comment Management module will have data related<br />
to the comments submitted by the user. What is this data apart from the comment<br />
itself? To answer this, first let us try to define the functionality of the Comment<br />
Management module in one line. &#8216;Comment management will manage comments<br />
submitted by a user for a particular story&#8217;—that&#8217;s how what will look like. The<br />
important point here is &#8216;comments submitted by a user for a particular story&#8217;. We<br />
have three main entities—Comments, Users, and Stories. Story and User entities<br />
have already been discussed in Chapters 3 and 4. So let us look at the Comments<br />
entity. The attributes for comments will include the date on which the comment has<br />
been added and the title of the comment. In short, the Comments entity will have the<br />
following attributes:</p>
<ul>
<li>Id—the unique number to identify each comment</li>
<li>Comment body—the text of the comment</li>
<li>Date—the date on which comment was added</li>
<li>User—the user who has added the comment</li>
<li>Story—the story on which the comment has been made</li>
</ul>
<p>The entity diagram for the Comments entity will be as follows:</p>
<p><center><img src="images/2009/09/usercomments/1.GIF"></center></p>
<p>Coming back to our one line definition, we know that the User, Story, and Comments<br />
entities are related. The question is how are they related? The answer is there in the<br />
one line definition itself. First, let us consider the User entity. The definition says<br />
&#8216;comments submitted by a user&#8217;. That means one user can submit many comments.<br />
Hence, the User entity has a one-to-many relationship with the Comments entity.<br />
The relationship will be as follows in terms of an E-R diagram:</p>
<p><center><img src="images/2009/09/usercomments/2.GIF"></center></p>
<p>The next part of the definition tells us &#8216;comments for a story&#8217;. This means that one<br />
story can have many comments. In other words, the Comments entity is related to<br />
the Story entity through a many-to-one relationship. The Story entity will be at the<br />
&#8216;one&#8217; end and the Comments entity will be at the &#8216;many&#8217; end of the relationship. The<br />
diagram will look like as follows:</p>
<p><center><img src="images/2009/09/usercomments/3.GIF"></center></p>
<p>When looking at all the entities with their attributes and relationships, the picture<br />
will be as follows:</p>
<p><center><img src="images/2009/09/usercomments/4.GIF"></center></p>
<p>The next step obviously is deriving the schema. Here it comes.</p>
<h2>Deriving the Schema</h2>
<p>We have the complete information about the attributes and relationships of the<br />
Comments entity. The main point about this entity is that unlike the User entity<br />
it doesn&#8217;t introduce any changes in the existing schemas. The reason is that the<br />
Comment entity is dependent on other entities and not vice versa. The schema will<br />
be as follows:</p>
<p><center><img src="images/2009/09/usercomments/5.GIF"></center></p>
<p>Here Story and User both have their own schemas. So their Ids will be the foreign<br />
keys in the table. Now, we can develop the table.</p>
<h2>Creating the Tables</h2>
<p>There is only one table to be created. Apart from the attributes, the comments table<br />
(keeping with the naming convention), will have two foreign key references—one to<br />
the users table and another to the tales table. Including these, the SQL query will be<br />
as follows:</p>
<p>
<pre><code>
	CREATE TABLE `comments` (
	`id` INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
	`comment_body` TEXT NOT NULL ,
	`submission_date` DATE NOT NULL ,
	`tale_id` INT NOT NULL,
	`user_id` INT NOT NULL,
	CONSTRAINT `fk_comments_users` FOREIGN KEY (`user_id`) REFERENCES
	users( `id`) ,
	CONSTRAINT `fk_comments_tales` FOREIGN KEY (`tale_id`) REFERENCES
	tales( `id`)
	) ENGINE = innodb;
</code></pre>
</p>
<p>That completes the table definition. By this time you will have started to think that<br />
if RoR is so productive, why do we still have to use the SQL statements to create<br />
tables?. There is another way—the Ruby way. We will see that in the next chapter<br />
where we will convert all the table creation statements using Ruby. Now that the<br />
required table has been defined, let us develop the modules starting with the<br />
Login management.</p>
<div class="wpInsert wpInsertInPostAd wpInsertBelow" style="margin: 5px; padding: 0px;"><script type="text/javascript"><!--
google_ad_client = "ca-pub-1490953723360528";
/* JB-Footer-LU 468x15 */
google_ad_slot = "8789107210";
google_ad_width = 468;
google_ad_height = 15;
//-->
</script>
<script type="text/javascript"
src="http://pagead2.googlesyndication.com/pagead/show_ads.js">
</script></div>]]></content:encoded>
			<wfw:commentRss>http://www.javabeat.net/2009/09/building-dynamic-web-2-0-websites-with-ruby-on-rails/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
	</channel>
</rss>
