CSC/ECE 517 Fall 2012/ch1 1w19 sa: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
(Created page with "==Introduction== <b> CRC Cards </b> also known as [http://en.wikipedia.org/wiki/Class-responsibility-collaboration_card <b> Class-Responsibility-Collaboration <sup></sup></b>] ca...")
 
No edit summary
Line 1: Line 1:
==Introduction==
==Introduction==
<b> CRC Cards </b> also known as [http://en.wikipedia.org/wiki/Class-responsibility-collaboration_card <b> Class-Responsibility-Collaboration <sup></sup></b>] cards are a brainstorming tool to enable collaboration across different teams or individuals in contribution to design, usually used in Object Oriented Software development. This was  proposed by <b>Ward Cunningham</b> and <b>Kent Beck</b><sup>[http://c2.com/doc/oopsla89/paper.html]</sup>. The CRC card can be viewed as an index card, with the following details:
'''Rails''' is a MVC (Model-View-Controller) based architecture for web development based on the Ruby language. Rails 2[http://guides.rubyonrails.org/2_3_release_notes.html] was released in December 2007. Initially Rails 2 supported Ruby 1.8[http://www.ruby-lang.org/en/news/2008/05/31/ruby-1-8-7-has-been-released/]. It now has been updated to support Ruby 1.9.1[http://www.ruby-lang.org/en/news/2009/01/30/ruby-1-9-1-released/]. Rails 3 which brings in many improvements over Rails 2 supports Ruby 1.9 and above. The current stable version of Rails is 3.2.8[http://rubyonrails.org/download] released on Aug 9, 2012.
[[Image:crc-card.gif|frame|right|CRC Card Structure]]
This wikibook chapter focuses mainly on the differences of Rails 2 and Rails 3.


:* The Top of the card usually bears the name of the class.
==Differences between Rails 2 and Rails 3==
:* The Left side of the card has the responsibilities of the class.
==='''Unobtrusive Javascript'''[http://en.wikipedia.org/wiki/Unobtrusive_JavaScript]===
:* The Right side of the card has the collaborating classes corresponding to each of the responsibilities listed in the left side.
In previous versions of Rails, JavaScript was generated inline with HTML, causing ugly and somewhat brittle code.
As an example, Rails allows you to use its link_to method to generate a delete link for some object.


Thus in general, a CRC session can be viewed as the interaction between a set of collaborating classes for a particular [http://en.wikipedia.org/wiki/Use_case Use case]. <br> <br> According to <sup>[http://www.extremeprogramming.org/rules/crccards.html]</sup><i>A CRC session proceeds with someone simulating the system by talking about which objects send messages to other objects. By stepping through the process weaknesses and problems are easily uncovered. Design alternatives can be explored quickly by simulating the design being proposed.</i>
<%= link_to "Delete this Post", @post, :confirm => "Do you really want to delete this post?", :method => :delete %>


===A CRC Example===
Using this method in your view would generate the following in Rails 2:
To better understand how the CRC cards work together, let us consider a simple student enrollment problem,where we are required to model the students enrolled in different courses. We can easily define the <b>Student CRC Card</b> as having attributes such as student name, student id and responsibilities that enable a student to enroll in a course or drop the course. In this particular instance, the collaborating class would be the <b>Course</b> class. The <b>Course CRC Card</b> can in turn be visualized as having its own responsibilities, such as having attributes like Course Id, course name and the collaborating class would be the <b>Instructor
<a href="/posts/6" onclick="if (confirm('Do you really want to delete this post?')) { var f = document.createElement('form');
class</b>. The CRC cards for the Student class and the Course Class are shown below.<br><br>
      f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
[[Image:Stud_enr_Crc.jpg|frame|center|Student and Course CRC Card]]
      var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
<br>
      m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete this Post</a>  
There are also several practical designs that use the CRC card model to design Object oriented software design. The  [http://www.extremeprogramming.org/example/crcsim.html Simulator for Coffee Maker] explores an [http://en.wikipedia.org/wiki/Extreme_Programming Extreme Programming] approach combined with CRC card technique to come up with a design for the coffee maker.
Rails 3 would generate something much simpler:


Another interesting approach using CRC cards explores a design for the [http://www.math-cs.gordon.edu/courses/cps211/ATMExample/CRCCards.html ATM Machine]
<a href='/posts/6"' rel="nofollow" data-method="delete" data-confirm="Do you really want to delete this post?">Delete this Post</a>
Rails 3 replaces all of the inline JavaScript with a couple of HTML5 attributes. All of the JavaScript event handlers to handle the actual confirmation box and deletion are stored in one central JavaScript file that is included with every rails project.


===Advantages of CRC cards===
==='''No more dependency on only Prototype Javascript library'''===
There are quite a few advantages of CRC cards that make it a preferable model in many designs. Some of the advantages of the CRC card design method are
One big advantage to this new method is that the JavaScript helpers are framework agnostic. Instead of being tied to the Prototype library like you were in Rails 2, you can now choose whatever JavaScript framework you like (Rails apps come with Prototype by default, but jQuery is now officially supported[https://github.com/rails/jquery-ujs].
<br>
:* CRC cards can allow designers to easily make audience understand a very complex system. In essence it allows for building more complex designs by slowly building the interactions between the collaborating classes, one by one.
:* CRC cards are a simple technique and it can be easily used by anyone with very little training and does not require any expensive computing resources(a board or a paper and a pen would suffice).
:* CRC is fundamentally a brainstorming tool, enabling different people in a team to come up with the design by collaborating, enabling everyone in the team to contribute
:* CRC can be used with other formal object oriented design methodologies such as [http://en.wikipedia.org/wiki/Extreme_Programming Extreme Programming] (an [http://en.wikipedia.org/wiki/Agile_Modeling Agile] development Technique) and can be used along with modelling languages such as [http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language(UML)]


==Why need a Software for CRC Cards==
==='''Improved Security'''===  
CRC cards are limited by their scope. If we go about designing a huge project, the scope spans many classes and interactions between them. The tedious task of maintaining are CRC cards and to properly formulate interaction can get overwhelming.  
Another awesome new feature of Rails 3 is that XSS[http://en.wikipedia.org/wiki/Cross-site_scripting] protection is now enabled by default. Rails 2 supported XSS protection through the use of the h method.
Following reasons propel use for software for CRC Cards :
<%= h @comment.text %>   
:* <b>Designing Scenario:</bA scenario represents series of steps in which classes and objects communicate. There are be references to other cards or scenarios.  
The h method would escape html and JavaScript to ensure that no malicious client-side code was executed. This method worked great, but there was one problem: you had to actually remember to use the h method everywhere the user entered input was displayed. If you forgot even one place, then you were vulnerable to an XSS attack.
:* <b>Modeling :</b>  Software provide an easy way to segregate cards and objects into different diagrams. Thus we can model our software with different functionality very easily.
In Rails 3, all input is escaped by default, taking the burden off of the developer of having to remember to escape everywhere that malicious code might be present. For those times that you do want to allow unescaped data to appear in your view, you can use the raw method to tell Rails 3 not to escape the data.
:* <b>Simulation :</b> Software can provides simulation of an software design. This might include single stepping backwards, forwards a scenario or jumping to a specific location in the scenario stack of a multiple scenario simulation
:* <b>Synchronization and Dependencies:</b> Software can maintain relationships between cards, scenarios as design changes take place. If a card references other cards or classes, those cards are generated automatically. Also any name changes and cross references between objects are instantly updated.  
:* <b>Revision history and Version Control :</b> Software for CRC cards supports changes to CRC cards. It is easy to model and keep track of all changes to a CRC cards. This is extremely helpful in realizing the design changes to CRC cards.


==Desining Software==
<%= raw @comment.text %> 
The following steps proceed while designing Software for CRC cards:


*<b>Create CRC Cards</b>
==='''New Query Engine'''===
A CRC model is usually created by an individual or small group of designers during the early phase of an object-oriented development project.The figure shows the design of hierarchy of classes. These set of class used for drawing objects are shown. We can see TShape class has a superclass called TObject and two subclasses, TBox and TCircle. Lets assume we create new class TWindow derived from the superclass TObject.  [[Image:Design.png|thumb|Description]]
Rails 3 includes a cool new query engine that makes it easier to get back the data you want and gives you more flexibility in your controller code. These changes show up in various places, but the most common case is fetching data in your controller. In Rails 2, you could use the find method to retrieve the data you were looking for, passing in arguments to specify conditions, grouping, limits, and any other query information. For example:


*<b>Assign Responsibilities</b>
@posts = Post.find(:all, :conditions => [ "category IN (?)", categories], :limit => 10, :order => "created_on DESC") 


Once a set of classes are defined, behaviors can be assigned that will provide the functions of the application. For example, the TShape card has responsibilities Initialize to create it and Draw to illustrate it on the diagram.
finds the first ten posts within some specified categories ordered by the creation time.


*<b>Add Attributes</b>
In Rails 3, each of the passed in parameters has its own method, which can be chained together to get the same results.


Attributes of classes may also be identified in a CRC Card.The TShape class has attributes fPosition, fType and
@posts = Post.where([ "category IN (?)", categories]).order("created_on DESC").limit(10)
fSelected.


*<b>Define and simulate Scenario</b>
The query is not actually executed until the data is needed; so these methods can even be used across multiple statements.


A scenario describes a sequence of steps in the design using the responsibilities of a group of collaborating
@posts = Post.where([ "category IN (?)", categories])
classes. Collaboration between classes refers to a client object that uses a responsibility performed
if(condition_a)
by a server object. Often a class must call upon several collaborating classes to implement one of its
@posts = @posts.where(['approved=?', true])
responsibilities.A scenario describes what happens in the system from a high-level, user point of view.
else
[[Image:Scenario.png|thumb|Description]]
@posts = @posts.where(['approved=?', false])
Consider situation to the right. We have defined two CRC cards with their responsibility. A scenario deinfes several steps. Each step in a scenario has a Client, Server and Responsibility field. For each step,
End
a client class uses a responsibility of a server class


The Open Document scenario in the picture references the Initialize Document subscenario
This is only a simple example, but should provide you with an idea of some of the ways this new syntax can be more useful.
by specifying its server class Document in the server field and its scenario name in the Responsibility field.
The first step in the Initialize Document subscenario uses Document as the server class name.


By single stepping forwards, backwards or through each subscenario, bugs in the design can be identified and corrected early.
==='''Easier Email'''===
The ActionMailer module has been rewritten to make it a lot easier for your application to send email in Rails 3.  


*<b>Partition the Design</b>
'''1-Default Setting'''
As the number of CRC cards in the design grows, they can be grouped by function. Using Software for CRC cards,
In Rails, a Mailer is a class that can have many methods, each of which generally configure and send an email. Previously, you had to set all of the parameters for each email separately in each method.
separate diagrams are used to partition the model into different subject areas.  


*<b>Inheritance Graph</b>
class UserMailer < ActionMailer::Base
An automated tool can generate an inheritance graph from information on CRC cards. This diagram can
def welcome_email(user)
concisely illustrate the big picture of a large project that might contain hundreds of classes and dozens of diagrams.
    from       "system@example.com"    # other paramters
end
def password_reset(user)
    from      "system@example.com"
    # other parameters
end
end


*<b>Verify Your Work </b>
In Rails 3, you can specify defaults that can be optionally overwritten in each method.


Creating and simulating scenarios will help verify that a design is correct and complete. A CRC software
class UserMailer < ActionMailer::Base
can perform other error checks to locate design problems.
  default :from => 'no-reply@example.com',
For example, responsibilities that are not used in any scenarios may indicate that the design is incomplete
          :return_path => 'system@example.com'
or perhaps the responsibility isn't needed.Likewise, a card that is not used by any collaboration
may not be needed.


==Summary==
def welcome_email(user)
Software for CRC cards are immensely helpful in designing and modeling Software development using CRC cards.As the size of object-oriented system grow, it becomes increasingly difficult to model the problem with index based CRC cards. Thus an automated tool is required to maintain design and clear functionality.
    # no need to specify from parameter
  end
end


==See Also==
'''2-Cleaner API'''
*[http://en.wikipedia.org/wiki/Unified_Modeling_Language Unified Modeling Language(UML)]
Previous versions of Rails required you to send email using special methods that were dynamically created by ActionMailer. For instance, if you wanted to deliver the welcome email in the example above, you would need to call:
*[http://en.wikipedia.org/wiki/Agile_Modeling Agile Modelling]
*[http://en.wikipedia.org/wiki/Extreme_Programming Extreme Programming]


==References==
UserMailer.deliver_welcome_email(@user) 
[1] A Laboratory For Teaching Object-Oriented Thinking: [http://c2.com/doc/oopsla89/paper.html http://c2.com/doc/oopsla89/paper.html]


[2] CRC Cards: [http://www.extremeprogramming.org/rules/crccards.html http://www.extremeprogramming.org/rules/crccards.html]
ln Rails 3, you can just call


[3] [http://www.extremeprogramming.org/example/crcsim.html A Simulator for Coffee Maker]
<b>UserMailer.welcome_email(@user).deliver  </b>


[4] [http://www.math-cs.gordon.edu/courses/cps211/ATMExample/CRCCards.html CRC Card for ATM]
This makes more sense semantically, and additionally allows you to retrieve and manipulate the Mail object before delivering the email.


==External Links==
==='''Dependency Management'''===
* [http://c2.com/doc/oopsla89/paper.html A Laboratory For Teaching Object-Oriented Thinking] by Ward Cunningham and Kent Beck
One of the strengths of the Ruby on Rails framework is the plethora of gems available for use by developers. Whether it's authentication[https://github.com/binarylogic/authlogic],
* [http://books.google.com/books?id=SGOyQai2TboC&printsec=frontcover&dq=CRC+card+book&hl=en&ei=xSOaTKSaNISclgfRqtkK&sa=X&oi=book_result&ct=result&resnum=1&ved=0CDYQ6AEwAA#v=onepage&q&f=false The CRC card book] by David Bellin, Susan Suchman Simone
handling financial[http://activemerchant.org/] transactions[https://github.com/thoughtbot/paperclip], handling file uploads, or nearly anything else, chances are a gem exists to help with your problem.


* [http://books.google.com/books?id=baopCOstm_kC&pg=PA29&lpg=PA29&dq=creating+software+for+CRC+cards&source=bl&ots=hABGQbbmXV&sig=CTHPtCN1GmZEyTAIPWvKE--8-M4&hl=en&ei=7ReaTISDKYL68Aadtq08&sa=X&oi=book_result&ct=result&resnum=9&ved=0CEsQ6AEwCDgK#v=onepage&q&f=false Using CRC Cards: An Informal Approach to Object-Oriented Development]
Issues can arise, however, if your gems require other gems, or developers are on different environments, among other things. To help solve these types of
* [http://www.agilemodeling.com/artifacts/crcModel.htm Modelling CRC Cards]
situations, Rails 3 adds the Bundler[http://gembundler.com/] gem to help manage your dependencies. Using Bundler in Rails 3 is extremely simple; add a line for each gem you
* [http://www.excelsoftware.com/quickcrcwin.html Quick CRC]
require in your Gemfile, a file included in the root of each of your applications.
 
<b>gem 'authlogic'</b>
Once you've included all your gems, run:
 
<b>bundle install</b>
 
and Bundler will download and configure all of the gems and their dependencies that you need for the project.
Bundler also allows you to specify certain gems to only be configured in certain environments (development vs production vs testing).
These are only a few of the many changes included in Ruby on Rails 3. Many of the old APIs still work in Rails, even if they've been deprecated, to make it easier to update.
 
==='''ActiveRecord finder methods'''===
<b>In Rails 2</b>
 
<b>User.find(:all, : order => "created_at desc", :limit => 5) </b>
 
Rails 3 looks at the hash of options that is being passed to find(:all, : order, and :limit) and replace each item in the hash with an equivalent method.
Rails 3 has a <b>new API</b> for the dynamic fiders
 
<b>where, having, select, group, order, limit, offset, joins, includes, ...</b>
 
So, in Rails 3 it becomes
 
<b>User.order("created_at desc").limit(5)</b>
 
==='''Active Record Validations'''===
There sre separate validations in Rails 2
 
<b>validates_presence_of :username
 
validates_uniqueness_of :username
 
validates_length_of :email, :maximum => 40 </b>
 
 
In Rails 3 these can be clubbed together
 
<b>validates :email, :presence => true,
 
:uniqueness => true,
 
:length => {:maximum => 30}</b>

Revision as of 00:11, 15 September 2012

Introduction

Rails is a MVC (Model-View-Controller) based architecture for web development based on the Ruby language. Rails 2[1] was released in December 2007. Initially Rails 2 supported Ruby 1.8[2]. It now has been updated to support Ruby 1.9.1[3]. Rails 3 which brings in many improvements over Rails 2 supports Ruby 1.9 and above. The current stable version of Rails is 3.2.8[4] released on Aug 9, 2012. This wikibook chapter focuses mainly on the differences of Rails 2 and Rails 3.

Differences between Rails 2 and Rails 3

Unobtrusive Javascript[5]

In previous versions of Rails, JavaScript was generated inline with HTML, causing ugly and somewhat brittle code. As an example, Rails allows you to use its link_to method to generate a delete link for some object.

<%= link_to "Delete this Post", @post, :confirm => "Do you really want to delete this post?", :method => :delete %>

Using this method in your view would generate the following in Rails 2: <a href="/posts/6" onclick="if (confirm('Do you really want to delete this post?')) { var f = document.createElement('form');

      f.style.display = 'none'; this.parentNode.appendChild(f); f.method = 'POST'; f.action = this.href;
      var m = document.createElement('input'); m.setAttribute('type', 'hidden'); m.setAttribute('name', '_method');
      m.setAttribute('value', 'delete'); f.appendChild(m);f.submit(); };return false;">Delete this Post</a> 

Rails 3 would generate something much simpler:

<a href='/posts/6"' rel="nofollow" data-method="delete" data-confirm="Do you really want to delete this post?">Delete this Post</a>

Rails 3 replaces all of the inline JavaScript with a couple of HTML5 attributes. All of the JavaScript event handlers to handle the actual confirmation box and deletion are stored in one central JavaScript file that is included with every rails project.

No more dependency on only Prototype Javascript library

One big advantage to this new method is that the JavaScript helpers are framework agnostic. Instead of being tied to the Prototype library like you were in Rails 2, you can now choose whatever JavaScript framework you like (Rails apps come with Prototype by default, but jQuery is now officially supported[6].

Improved Security

Another awesome new feature of Rails 3 is that XSS[7] protection is now enabled by default. Rails 2 supported XSS protection through the use of the h method. <%= h @comment.text %> The h method would escape html and JavaScript to ensure that no malicious client-side code was executed. This method worked great, but there was one problem: you had to actually remember to use the h method everywhere the user entered input was displayed. If you forgot even one place, then you were vulnerable to an XSS attack. In Rails 3, all input is escaped by default, taking the burden off of the developer of having to remember to escape everywhere that malicious code might be present. For those times that you do want to allow unescaped data to appear in your view, you can use the raw method to tell Rails 3 not to escape the data.

<%= raw @comment.text %>

New Query Engine

Rails 3 includes a cool new query engine that makes it easier to get back the data you want and gives you more flexibility in your controller code. These changes show up in various places, but the most common case is fetching data in your controller. In Rails 2, you could use the find method to retrieve the data you were looking for, passing in arguments to specify conditions, grouping, limits, and any other query information. For example:

@posts = Post.find(:all, :conditions => [ "category IN (?)", categories], :limit => 10, :order => "created_on DESC")

finds the first ten posts within some specified categories ordered by the creation time.

In Rails 3, each of the passed in parameters has its own method, which can be chained together to get the same results.

@posts = Post.where([ "category IN (?)", categories]).order("created_on DESC").limit(10)

The query is not actually executed until the data is needed; so these methods can even be used across multiple statements.

@posts = Post.where([ "category IN (?)", categories]) if(condition_a)

@posts = @posts.where(['approved=?', true])

else

@posts = @posts.where(['approved=?', false])

End

This is only a simple example, but should provide you with an idea of some of the ways this new syntax can be more useful.

Easier Email

The ActionMailer module has been rewritten to make it a lot easier for your application to send email in Rails 3.

1-Default Setting In Rails, a Mailer is a class that can have many methods, each of which generally configure and send an email. Previously, you had to set all of the parameters for each email separately in each method.

class UserMailer < ActionMailer::Base def welcome_email(user)

   from       "system@example.com"    # other paramters

end

def password_reset(user)
   from       "system@example.com"
   # other parameters
end

end

In Rails 3, you can specify defaults that can be optionally overwritten in each method.

class UserMailer < ActionMailer::Base

 default :from => 'no-reply@example.com',
          :return_path => 'system@example.com'
def welcome_email(user)
   # no need to specify from parameter
 end

end

2-Cleaner API Previous versions of Rails required you to send email using special methods that were dynamically created by ActionMailer. For instance, if you wanted to deliver the welcome email in the example above, you would need to call:

UserMailer.deliver_welcome_email(@user)

ln Rails 3, you can just call

UserMailer.welcome_email(@user).deliver

This makes more sense semantically, and additionally allows you to retrieve and manipulate the Mail object before delivering the email.

Dependency Management

One of the strengths of the Ruby on Rails framework is the plethora of gems available for use by developers. Whether it's authentication[8], handling financial[9] transactions[10], handling file uploads, or nearly anything else, chances are a gem exists to help with your problem.

Issues can arise, however, if your gems require other gems, or developers are on different environments, among other things. To help solve these types of situations, Rails 3 adds the Bundler[11] gem to help manage your dependencies. Using Bundler in Rails 3 is extremely simple; add a line for each gem you require in your Gemfile, a file included in the root of each of your applications.

gem 'authlogic' Once you've included all your gems, run:

bundle install

and Bundler will download and configure all of the gems and their dependencies that you need for the project. Bundler also allows you to specify certain gems to only be configured in certain environments (development vs production vs testing). These are only a few of the many changes included in Ruby on Rails 3. Many of the old APIs still work in Rails, even if they've been deprecated, to make it easier to update.

ActiveRecord finder methods

In Rails 2

User.find(:all, : order => "created_at desc", :limit => 5)

Rails 3 looks at the hash of options that is being passed to find(:all, : order, and :limit) and replace each item in the hash with an equivalent method. Rails 3 has a new API for the dynamic fiders

where, having, select, group, order, limit, offset, joins, includes, ...

So, in Rails 3 it becomes

User.order("created_at desc").limit(5)

Active Record Validations

There sre separate validations in Rails 2

validates_presence_of :username

validates_uniqueness_of :username

validates_length_of :email, :maximum => 40


In Rails 3 these can be clubbed together

validates :email, :presence => true,

uniqueness => true,
length => {:maximum => 30}