Showing posts with label Rails Action. Show all posts
Showing posts with label Rails Action. Show all posts

Sunday, September 12, 2010

Don't repeat yourself

The DRY (Don't Repeat Yourself) Principle states:
Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.

This is regarded as the fundamental principle of rails development.The principle was formulated by Andy Hunt and Dave Thomas in The Pragmatic Programmer, and underlies many other well-known software development best practices and design patterns.Inorder to explain the principle in detail lets derive the following aspects

  • Duplication is waste

Every line of code that goes into an application must be maintained, and is a potential source of future bugs. Duplication needlessly bloats the codebase, resulting in more opportunities for bugs and adding accidental complexity to the system. The bloat that duplication adds to the system also makes it more difficult for developers working with the system to fully understand the entire system, or to be certain that changes made in one location do not also need to be made in other places that duplicate the logic they are working on. DRY requires that "Every piece of knowledge must have a single, unambiguous, authoritative representation within a system."

  • Repetition in process calls for automation

Many processes in software development are repetitive and easily automated. The DRY principle applies in these contexts as well as in the source code of the application. Manual testing is slow, error-prone, and difficult to repeat, so automated test suites should be used, if possible. Integrating software can be time consuming and error-prone if done manually, so a build process should be run as frequently as possible, ideally with every check-in. Wherever painful manual processes exist that can be automated, they should be automated and standardized. The goal is to ensure there is only one way of accomplishing the task, and it is as painless as possible.

  • Repetition in logic calls for abstraction

Repetition in logic can take many forms. Copy-and-paste if-then or switch-case logic is among the easiest to detect and correct. Many design patterns have the explicit goal of reducing or eliminating duplication in logic within an application. If an object typically requires several things to happen before it can be used, this can be accomplished with an Abstract Factory or a Factory Method. If an object has many possible variations in its behavior, these behaviors can be injected using the Strategy pattern rather than large if-then structures. In fact, the formulation of design patterns themselves is an attempt to reduce the duplication of effort required to solve common problems and discuss such solutions. In addition, DRY can be applied to structures, such as database schema, resulting in normalization.

Convention over configuration

This is actually coding by conventions.This software design paradigm which ensures the following things
  • This decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility
  • The developer only needs to specify unconventional aspects of the application for example if there is a class called user in the model then its curresponting table will be Users
General-purpose frameworks usually require one or more configuration files in order to set up the framework. A configuration file provides a mapping between a class and a resource (a database) or an event (a URL request). As the size and complexity of applications grow, so do the configuration files, making them harder to maintain.

A Valid example in rails is as below

An example should show you how the conventions work together: You have a database table called users with the primary key id. The matching model is called user and the controller, that handles all the logic is named users_controller. The view is split in different actions: if the controller has a new and edit action, there is also a new- and edit-view.

class NamesValidator

# Checks that first_name and last_name are within certain length
def self.valid_length?(name)
 name.first_name.length < 20 and name.last_name.length < 10
end

# Checks that first_name and last_name have the first character capitalized
# capitalize turns HELLO into Hello; hello into Hello; etc
def self.valid_case?(name)
 name.first_name == name.first_name.capitalize and
 name.last_name == name.last_name.capitalize
end

def self.non_conforming_method
 # This method will not be called during validation
end

end

class Name < Validatable

attr_accessor :first_name, :last_name # create getters and setters for instance variable name

def initialize(first_name, last_name)
 @first_name, @last_name = first_name, last_name
end

end

Name is just a simple class that has two fields: first_name and last_name. The NamesValidator has two class methods that check if the name is of valid length and if it has the right case. The method non_conforming_method is left there to show that our validation system does not call that method since it does not conform to the naming convention we agreed upon.

Saturday, September 11, 2010

The MVC Architecture (MVC)

I am happy to know that you all get a good knowledge about the rails Introduction post.So lets move to the working principle action in rails application Model–View–Controller (MVC) is a software architecture,currently considered an architectural pattern used in software engineering. The pattern isolates "domain logic" (the application logic for the user) from input and presentation (UI), permitting independent development, testing and maintenance of each.For instance, as depicted in the figure below, you may refer to "controller" as "input", "model" as "processor" or "processing" and "view" as "output". The MVC Architecture (MVC) So in other words, controller receives the input, passes it to the model for processing, or to the view for output. So MVC benefits include:
  • Isolation of business logic from the user interface
  • Ease of keeping code DRY
  • Making it clear where different types of code belong for easier maintenance
Let Us explain each in detail mentioning each functionalities

1) Model

A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. In most cases, one table in your database will correspond to one model in your application. The bulk of your application’s business logic will be concentrated in the models.

2) View

The view renders the model into a form suitable for interaction, typically a user interface element. Multiple views can exist for a single model for different purposes. A viewport typically has a one to one correspondence with a display surface and knows how to render to it.

3) Controller

The controller receives input and initiates a response by making calls on model objects. A controller accepts input from the user and instructs the model and viewport to perform actions based on that input.

The MVC Architecture (MVC)

So the steps involved in the working of MVC is as follows

  • The browser makes a request, such as http://rubyonrailslink.blogspot.com/2010/09/what-is-rails.html
  • web server (mongrel, WEBrick, etc.) receives the request. It uses routes to find out which controller to use: the default route pattern is “/controller/action/id” as defined in config/routes.rb. In our case, it’s the “video” controller, method “show”, id “15″. The web server then uses the dispatcher to create a new controller, call the action and pass the parameters.
  • Controllers do the work of parsing user requests, data submissions, cookies, sessions and the “browser stuff”. They’re the pointy-haired manager that orders employees around. It gives orders without knowing (or caring) how it gets done. In our case, the show method in the video controller knows it needs to lookup a video. It asks the model to get video 15, and will eventually display it to the user.
  • Models are Ruby classes. They talk to the database, store and validate data, perform the business logic and otherwise do the heavy lifting. In this case, the model retrieves video 15 from the database.
  • Views are what the user sees: HTML, CSS, XML, Javascript, JSON. They’re the sales rep putting up flyers and collecting surveys, at the manager’s direction. Views are merely puppets reading what the controller gives them. They don’t know what exactly happening in the back room. In our example, the controller gives video 15 to the “show” view. The show view generates the HTML: divs, tables, text, descriptions, footers, etc.
  • The controller returns the response body (HTML, XML, etc.) & metadata (caching headers, redirects) to the server. The server combines the raw data into a proper HTTP response and sends it to the user.