Search This Blog

2015-01-26

Create an Agnostic Vendor Infrastructure in Ruby

Depending how the code was written adding new services to it can be difficult.
For instance, let's say we are building a rails application that gets integrated to cloud storage vendors.
A naive implementation would be to directly integrate to a cloud storage specific APIs.
In this case when new cloud storage vendors are added it is very probable that several nasty case... when ... end statements would be inserted in code.

When a new cloud storage service is added the developer must remember all places where those growing case-like statements are inserted. This makes the system more susceptible to errors due to  changes in several parts of the code. This problem is explained in detail by the shotgun surgery anti-pattern (http://en.wikipedia.org/wiki/Shotgun_surgery)

The rest of the system shouldn't be aware that a new cloudstorage service was added. That is where a combination of design patterns come in handy:
  • a facade to provide a simple interface for cloud storage operations 
  • a service locator to find the right cloud storage adapter
  • a cloud storage adapters that make each vendor API compliant to a single defined interface that can be understood by the facade


1) Cloud Storage Facade

2) Cloud Storage Adapter Locator

3) Cloud Storage Adapters

Note that this combination of patterns can be used to abstract many other types of services. Cloud storage service was just an example used here.

2013-12-18

Rails: New Framework - Old Design Problems

I have been programming for Rails for about 2-3 years now. As I came from a C# background it was a bit awkward for me to see some design principles I took as good practices being unashamedly broken such as:

  • data-driven models mixed with persistence logic instead of plain old domain objects
  • controllers being used as application scenarios instead of coordinators between my actual application object and the view ( that was my understanding of MVC )
At that time I just thought it was the ruby-on-rails way of doing things and as a good newcomer in the ruby developer community I decided I should learn and listen more from other rails developers and forums than telling what the best practices should be.

However after some years of work experience I realized some of those design problems were not sufficiently addressed for some anti-patterns: ( At least not until this year - some problems are still not addressed )
  • fat controllers / skinny models
  • skinny controllers / fat models
  • god models
  • transparent polyglot persistence in domain models ( SQL, NoSQL, Graph, etc ... )
Note that these design problems were solved in other programming environments long ago.

Now with the maturity of rails developer community and the increasing adoption of rails in many enterprises I see design patterns and ideas being presented more often. 
The objective of these ideas seems to be the same: keep active record models focused only on data and extracting out logic of any kind ( business, view, etc.. ) to other classes or modules.
Some ideas that called my attention are:
  • Use of service objects that orchestrate rails models in handling complex scenarios
  • Use of rails concerns (modules) to extract behavior or methods that do not belong to the model responsibility (which in rails means data persistence and validation)
Some oppose to rails concerns because it can lead your rails model class to have many roles instead of one-role. ( This is a popular clean code principle: one class, one role )
However in his article DHH gave good reasons for doing it what actually made me open an exception for this clean code principle for this particular ruby case. ( I am a clean code fan and exceptions are rare)

In this case this clean code principle of one-role-class became a bit different for me after reading DHH article (see reference below in chubby models): 
  • one class should have one IMPLEMENTATIONAL role. 
In Ruby a rails model should implement only ONE role while it can be injected by many others.
For instance it is not a problem that your class contain many roles since they come from mixins.
However mixins (or Rails concerns) should augment the rails model features and not make your class implementation dependent on them. It is not forbidden to be dependent on mixins such as by active record or mongoid since they are part of the one implementational role defined for the class but some caution is needed.

In the other hand the idea of using a service object can make it clear that some complex business concepts are executed separately. Scenarios include payment process, authentication and many others. Its benefit is very clear to me.

Both ideas are of great help to keep both controllers and models on a diet ( skinny controller / skinny models ) but other design problems such as transparent polyglot persistence and possible many others remain unanswered.

I hope to see what the ruby community will have to say about that in the future.
Maybe I can answer some of those questions, who knows ?

References:









2012-12-06

RORM - Ruby Domain Objects with Persistence

After some time using ActiveRecord and MongoId, I decided it was time to create a ruby ORM for domain objects as my first github project.
https://github.com/hcmarchezi/rorm/blob/master/README.md

2012-11-12

Separated Interface Design Pattern


When developing a system in many cases it is possible to identify dependencies among different layers whose responsibilities are well defined in the system.

Some examples of layer dependencies are:
  • Controller layer dependency and UI layer
  • Domain logic layer and persistence layer

One strategy to remove dependencies between layers is to use the separated interface design pattern. This pattern consists of defining an interface from the bottom layer that is going to be used by the top layer. See diagram below  to understand how it works for controller and UI layer:


The controllers in the example above only reference interface views and never know which view implementation they are actually working with.

This design pattern is recommended for a system when:
  • One layer (such as a controller) will be reused to be plugged into different versions of the other layer (such as HTML5 and native view layer implementations)
  • Layers are easier to be tested in isolation
  • It is not desired that one layer has API dependencies from the other layer

References:




2011-08-28

JavaScript: Object Oriented Programming

By using functions and the structures above it is possible to a function object which syntax works just like a C++/Java class. See examples below.

Classes

In JavaScript classes are declared as functions.
function Task(name,dueDate)
{
    this.name = name;
    this.dueDate = dueDate;
};
var myTask = new Task("Clean house","2011-07-01");
myTask.name = "some new name";

Methods

Methods are declared by extending the function prototype.
var User = function(email,password) {
    this.email = ""; // public field
    this.password = "";
};
User.prototype.generatePassword = function() {  // public method
    this.password = "generatedpass";
}
var user = new User("you@email.com","mypassword");
user.generatePassword(); // password is generatedpass
Alternatively methods can be declared inside the function declaration.
var User = function(email,password) {
    this.email = "";
    this.password = "";
    this.generatePassword = function() { 
        this.password = "generatedpass";
    };
};

Inheritance

In order to make a class inherit from another class, the subclass prototype must be set to the desired parent object. It is also necessary to set the constructor as the current class which is a little od. See example below.
function Person() {
    this.firstname = "James";
};
Person.prototype.generateName = function() {
    this.firstname = "generatedname";
};

function Student() {
    this.school = "Rahway School";
};
Student.prototype = new Person();
Student.prototype.constructor = Student;
Student.prototype.setBestSchool = function() {
    this.school = "Best school in town";
};

Polymorphism

Polymorphism can be achieved by simply declaring methods with the same name. Consider the hierarchy of figures as an example below.
function Photo() {    
}
Photo.prototype.getDestinationPath = function() { 
    return "./photos/common";
};
function PartyPhoto() {
}
PartyPhoto.prototype = new Photo();
PartyPhoto.prototype.constructor = PartyPhoto;
PartyPhoto.prototype.getDestinationPath = function() {
    return "./photos/parties";
};

photo = new Photo();
photo.getDestinationPath(); // path for common photos

partyPhoto = new PartyPhoto();
partyPhoto.getDestinationPath(); // path for party photos

Encapsulation

In the examples above all attributes and methods were public. In order to declare private attributes or methods one solution is to follow the template code below: (taken from http://www.codeproject.com/KB/scripting/jsoops.aspx )
function MyClass(){    
    //Private members
    return{
        //Public members
    }}
An App class can be implemented as:
function App(appname,description) {
    var _name = appname;
    var _description = description
    return {
        getName: function() { return _name; },
        getDescription: function() { return _description; },
        setName: function(appname) { _name = appname; },
        setDescription: function(description) { _description = description; }
    };    
}
var myApp = new App("voila","my game");
var.setName("other game");
Please note that this approach does not offer a way to have encapsulation and inheritance at the same time. Read next section to know one way to achieve this.

Inheritance with Encapsulation

By experimenting with the approach above, I found out a different way that made it possible to have both encapsulation and inheritance in JavaScript. The idea is to declare private members as function variables as above and then augment the parent object with the desired public functions. Thus it is not necessary to work with prototypes. Take the generic Person class as an example:
function Person(name) {
    // Private Members
    var _name = "";
    // Public Members (accesses private members)
    var obj = new Object();
    obj.setName = function(name) { _name = name; };
    obj.getName = function() { return _name;  };  
    // Constructor
    obj.setName(name);
    return obj;
};
A person instance will have access to getName and SetName but not _name attribute and therefore we have encapsulation. For a Student class that inherits from Person, the code would be:
function Student(name,school) {
    // Private Members
    var _school = "";
    // Creating parent object: Studen inherits from Person
    var parent = new Person(name);
    // Augmenting parent object with Student methods
    parent.setSchool = function(school) { _school = school; };
    parent.getSchool = function() { return _school; };
    // Constructor Logic (Initialization)
    parent.setSchool(school);
    return parent;
};
These functions can be used just like normal classes:
var person = new Person("James");
person._name; // undefined
person.getName(); // James

var student = new Student("Jack","Orange City School");
student._name;        // undefined
student.getName();  // Jack
student._school;       // undefined
student.getSchool(); // Orange City School

2011-02-27

iPhone Development: to Objective-C or not to Objective-C ?

When I think of Objective-C, what comes to my mind is a niche programming language for the MacOS and Apple related products. Thus as far as I know this is the only officially supported language to develop products for iPhones, iPods, iPads and so on ....
On the other hand I really what to develop apps that will work in Windows, Linux and MacOS, and for this purpose I see two options:

1) Develop in C/C++ and try to find tools that translate this code to Objective-C and/or MacOS

2) Use Objective-C to develop any kind of application (at least desktop and mobile apps)

Developing portable iPhone apps outside Objective-C


Swig

For the first option, there is swig ( http://www.swig.org/ ) which is a wrapper for C++ to export its classes and/or functions to several languages (Objective-C is a work in progress).
However it doesn´t really solve the problem because there are libraries.

Mono Touch

The Mono Touch ( http://monotouch.net/ ) is probably one of the most interesting project to develop apps for the iPhone without Objective-C. It makes it possible to develop apps with C#.NET. The same Mono project also make it possible to develop apps for Linux. As a consequence, C#.NET could be seriously considered to develop apps for a wide range of platforms. However unlike Mono one must pay to start using it which may not be a problem if you are familiarized with C#.NET.

PhoneGap

Another options is PhoneGap ( http://www.phonegap.com ) which is an open-source framework whose objective is to let developers to write apps with HTML5+CSS+JavaScript and execute it to the different mobile platforms including iOS.

Objective-C as a portable programming language


I recently read about he mechanics and philosophy of Objective-C language and I got quite impressed by its features. It is not just C with classes as I heard before, it is actually a powerful dynamic language. Everything is an object including the classes itself what reminds me of Smalltalk, LISP and Python.

There are also some options to use Objective-C outside of the Apple ecosystem:

GNU Step

As stated in their website ( http://www.gnustep.org/ ) the objective is to create an open version of Cocoa (former NextStep) for several platforms including Linux and Windows.

Besides porting the API this project also comes with several developer tools such as an IDE named ProjectCenter and a GUI code generator called Gorm.

Publishing ClickOnce winforms applications with command-line MSBuild

One of the most interesting characteristics of tools such as CCNet and Nant is the automated deploy. I found many examples of how to publish an application with pre-configured projects with click-one but I wanted to do it different. In order to make the project file cleaner the approach was to remove all click-once configurations from the project(*.csproj) so that command-line MSBuild will take care of publication configuration in a NAnt script. After some full-days of research, I found the solution below. I hope it helps in your project.
<exec program="${dotnetFrameworkDir}\MSBuild.exe">
  <arg value="${basePath}\MyProject\MyProject.csproj"></arg>
  <arg value="/target:publish"></arg>
  <arg value="/p:IsWebBootstrapper=true"></arg>
  <arg value="/p:SignManifests=true"></arg>
  <arg value="/p:ManifestKeyFile=${basePath}\MyProject\MyCertificate.pfx"></arg>
  <arg value="/p:TargetZone=LocalIntranet"></arg>
  <arg value="/p:GenerateManifests=true"></arg>
  <arg value="/p:PublishUrl=${clickOnceDir}"></arg>
  <arg value="/p:Install=true"></arg>
  <arg value="/p:InstallFrom=Web"></arg>
  <arg value="/p:UpdateEnabled=true"></arg>
  <arg value="/p:UpdateRequired=true"></arg>
  <arg value="/p:InstallUrl=http://myPublishUrlAddress"></arg>
  <arg value="/p:TargetCulture=pt-BR"></arg>
  <arg value="/p:ProductName=MyProject"></arg>
  <arg value="/p:PublisherName=MyCompany"></arg>
  <arg value="/p:MinimumRequiredVersion=${CCNetLabel}"></arg>
  <arg value="/p:CreateWebPageOnPublish=true"></arg>
  <arg value="/p:WebPage=${webPage}"></arg>
  <arg value="/p:OpenBrowserOnPublish=false"></arg>
  <arg value="/p:ApplicationRevision=17"></arg>
  <arg value="/p:ApplicationVersion=${CCNetLabel}"></arg>
  <arg value="/p:CreateDesktopShortcut=true"></arg>
  <arg value="/p:PublishWizardCompleted=true"></arg>
  <arg value="/p:BootstrapperComponentsLocation=Absolute"></arg>
  <arg value="/p:BootstrapperComponentsUrl=${bootstrapperUrl}"></arg>
  <arg value="/p:GenerateBootstrapperSdkPath=${pathBootStrapper}"></arg>
  <arg value="/p:UpdateUrlEnabled=false"></arg>
</exec>

2010-06-03

Tools and Utilities for the .NET Developer

Here is a list I got from the internet that might be useful (at least for a while):

http://geekswithblogs.net/mbcrump/archive/2010/05/25/tools-and-utilities-for-the-.net-developer.aspx

2010-05-09

Using Fluent Builder Pattern to Configure Test Objects

Depending on the complexity of the domain model, configuring mock objects for specific cenarios can make the resulting test code to get messy.

Consider the situation below with C#, NUnit and Moq framework

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  Mock somePaymentOptionMock = new Mock();
  Mock debTypeMock = new Mock();
  debtTypeMock
    .Setup(debtType.GetPaymentOptions())
    .Returns(new List(){somePaymentOptionMock.Object});

  Mock anotherPaymentOptionMock = new Mock();

  Mock debtMock = new Mock();
  debtMock.Setup(debt.DebtType).Returns(debTypeMock.Object);            

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List() { debtMock.Object },
      SelectedPaymentOption =  anotherPaymentOptionMock.Object
    });
}

A developer who reads the unit test can take a consirable amount of time to understand what is actually being tested even if a well-designed mock framework such as Moq is in use. Most of this work is about configuring mock objects. Besides the code size, the unit test doesn´t speak the language of the domain (business) and thus it becomes a mass of meaningless mock configuration.
I am on my way to learn how to apply TDD effectvely in software development and I quickly realized that the quality of unit tests are very important in order to this kind of methodology to succeed.

Accidentally some days I read an interesting post from Andrian about Rich Domain Tests at http://adrianhummel.wordpress.com/ and I decided to apply his idea.
After reading his post I got to the conclusion that one way to solve or at least minimize this unit-test-messy-code-problem was by using a fluent builder pattern to configure mock objects by using a builder whose interface could be describe how I am configuring a mock object with an interface closer to domain language.

The unit test below is a rewritten from the example above with the concepts described here:

[Test]
[ExpectedException(InvalidPaymentAgreementException)]
public void PaymentAgreementMustNotBeCreatedWhenThePaymentOptionIsNotValidForTheDebtType()
{
  PaymentOption somePaymentOption = PaymentOptionMockBuilder
                                    .Begin()
                                    .BuildPaymentOption();

  DebtType debtType = DebtTypeMockBuilder
                      .Begin()  
                      .AddPaymentOptionOf(somePaymentOption)
                      .BuildDebtType();
            
  PaymentOption anotherPaymentOption = PaymentOptionMockBuilder
                                       .Begin()
                                       .BuildPaymentOption();          
            
  Debt debt = DebtMockBuilder
              .Begin()
              .WithDebtTypeOf(debtType)
              .BuildDebt();

  PaymentAgreement paymentAgreement = new PaymentAgreement(
    new PaymentAgreementCreationParameter()
    {
      AgreementYear = SystemDate.Get().Value.Year,
      AgreementNumber = 1,
      AgreementCreationDate = SystemDate.Get().Value.Date,
      NumberOfInstallments = 1,
      AgreementValue = 100.0m,
      Debts = new List &lt Debt &gt () { debt},
      SelectedPaymentOption =  anotherPaymentOption
    });

}

The fluent builder for Debt is DebtMockBuilder and can be programmed as follows:

    public class DebtMockBuilder
    {
        private Mock _debtMock;

        public static DebtMockBuilder Begin()
        {
            DebtMockBuilder builder = new DebtMockBuilder();
            builder._debtMock = new Mock();
            return builder;
        }

        public Debt BuildDebt()
        {
            return _debtMock.Object;
        }

        public DebtMockBuilder WithDebtTypeOf(DebtType debtType)
        {
            this._debtMock.Setup(debt => debt.DebtType).Returns(debtType);
            return this;
        }
    }

PaymentOptionMockBuilder follows the same idea.

Although I see that some improvements are needed I could see the following advantages from fluent mock builders:

  • The test code was easier to understand because domain terms were applied instead of specific API language.


  • Specific mock framework calls were encapsulated which theoretically can let programmers to use another mock framework in other projects or using more than one mock framework in the same test (I dont know why someone would do such a thing...).


  • Finally mock configuration becomes more flexible since existing methods don´t have to be modified to include new configuration but only a new configuration method is needed. Thus mock configuration can evolve as needed without loosing the domain interface.

2010-05-08

Test-Driven-Development Best Practices

I recently read a very intersting conversation in StackOverflow.com about test-driven development. I found it very instersting and the principles can be summarized as follows: (not ordered by importance)

1. Write the test first, then the code. Reason: This ensures that you write testable code and that every line of code gets tests written for it. 



2. Design classes using dependency injection. Reason: You cannot mock or test what cannot be seen. 


3. Separate UI code from its behavior using Model-View-Controller or Model-View-Presenter. Reason: Allows the business logic to be tested while the parts that can't be tested (the UI) is minimized. 


4. Do not write static methods or classes. Reason: Static methods are difficult or impossible to isolate and Rhino Mocks is unable to mock them. 


5. Program off interfaces, not classes. Reason: Using interfaces clarifies the relationships between objects. An interface should define a service that an object needs from its environment. Also, interfaces can be easily mocked using Rhino Mocks and other mocking frameworks. 


6. Isolate external dependencies. Reason: Unresolved external dependencies cannot be tested. 


7. Mark as virtual the methods you intend to mock. Reason: Rhino Mocks is unable to mock non-virtual methods.

8. Use creational design patterns. This will assist with DI, but it also allows you to isolate that code and test it independently of other logic.



9. Write tests using Bill Wake's Arrange/Act/Assert technique. This technique makes it very clear what configuration is necessary, what is actually being tested, and what is expected.


10. Don't be afraid to roll your own mocks/stubs. Often, you'll find that using mock object frameworks makes your tests incredibly hard to read. By rolling your own, you'll have complete control over your mocks/stubs, and you'll be able to keep your tests readable. (Refer back to previous point.)


11. Avoid the temptation to refactor duplication out of your unit tests into abstract base classes, or setup/teardown methods. Doing so hides configuration/clean-up code from the developer trying to grok the unit test. In this case, the clarity of each individual test is more important than refactoring out duplication.


12. Implement Continuous Integration. Check-in your code on every "green bar." Build your software and run your full suite of unit tests on every check-in. (Sure, this isn't a coding practice, per se; but it is an incredible tool for keeping your software clean and fully integrated.)

Reference: http://stackoverflow.com/questions/124210/best-practices-of-test-driven-development-using-c-and-rhinomocks

2010-02-24

Name Convention for Object Oriented Apps

Some time ago I came across with a question about naming conventions for different parts of the software: UI, Service, Entities, etc. I decided to share some of the conventions I have been using.


Naming Convention: ( Most used ):

Entities: As it is part of the domain package, no prefixes or suffixes here: Ex: Car, Client, etc.

Repository: Usually a suffix Repository. Ex: ClientRepository, CarRepository, etc.

ValueObject: Value objects are part of the domain so it follows entity´s convention. Ex: Money, Address, etc.

DTO: Usually a suffix DTO. Ex: ClientRegistrationDTO, CarRentDTO, AddressDTO, etc.

Service: Usually a suffix Service. Ex: ClientRegistrationService, CarRentService, etc.

Namespace Convention: (My Suggestion)

Entities, ValueObjects, Repositories Interfaces, Domain Services (Domain Layer)
..Domain.
Ex: Acme.Finantial.Domain.Debt,
      Acme.HR.Domain.CheckOvertimeService,
      Acme.Core.Domain.IPersonRepository    

Application Services 
..Service.
Ex: Acme.Sales.Service.ClientRegistrationService

Presentation Layer
..Presentation.
Ex: Acme.HR.Presentation.IClientRegistrationView, Acme.HR.Presentation.WebClientRegistration

Persistence Layer
..Persistence.
Ex: Acme.Core.Persistence.PersonRepositoryImpl (<--- implementation in NH, for example)

2010-02-22

Unit Testing Linq Queries in Moq

After some google research and experimentation I found that it was not worth to mock methods that return IQueryable or IQueryable because in order to use it programmers have to make use of extension methods. And this kind of methods are not supported by Moq ( a minimalistic mock framework ). This is the DAO interface I want to test.
public interface IDAOFactory
{
  public abstract IQueryable Query();
}
This is the moq unit test that fails, since I can´t use Linq directly.
[Test]
public void LinqQueryTest()
{ 
  // This moq configuration will trigger an exception – Can´t make use of extension methods
  daoFactoryMock.Setup(d => (from o in d.Query()
    where o.Id >= 0
    select o.Id).ToList())
    .Returns( new List() { 1, 2 } );
}
It turns out that the solution is easily solved by using a collection as a data source.
[Test]
public void LinqQueryTest()
{
  // Creates a IQueryable from a Collection
  IList lstOrders = new List() { 
    orderMock1.Object, 
    orderMock2.Object, 
    orderMock3.Object };
  IQueryable orderQuery = lstOrders.AsQueryable();

  // Configures the Query to return IQueryable implementation
  daoFactoryMock.Setup(d => d.Query()).Returns(orderQuery);

  // Now the linq queries can be used naturally 
  IList lstResult = (from o in daoFactoryMock.Object.Query() where o.Id >= 0 Select o).ToList();

  // Checking output results
  Assert.AreEqual(3, lstResult.Count);
}
It is important to notice that the collection elements that should also be mock objects must contain all the necessary data in order to make the correct test.

2009-12-26

Model View Controller with Events in .NET

This is often a confused design pattern and its main purpose is to separate objects that assume different roles in a software.
These roles are:
  • models - objects that actual execute the system tasks
  • views - objects that display the system data
  • controllers - objects that capture the user intentions from the view and route to the right actions
Usually Views have a reference to the controller however another approach below shows how to decouple the views from the controllers.
Views can be implemented in several ways depending on the UI library. For that reason, views are better represented as interfaces. However in order to reduce coupling between views and controllers, events can be used in the interface views.
The example below shows a client registration view:
using System;
namespace MyController
{
  public interface IClientRegistrationView
  {
    public long Id { get; set; }
    public string Name { get; set; }
    public string Registration { get; set; }
    public event ClientEventHandler InsertRequested;
    public event ClientEventHandler UpdateRequested;
    public event ObjectIdEventHandler &lt long &gt RemoveRequested;
    public event ObjectIdEventHandler &lt long &gt RetrieveRequested;
  }
}
Specific event arguments were also created for the Client Registration View:
  • ClientEventArgs - contains client fields so that it can be sent to the underlying layer.
  • ObjectIdEventArgs - contains a generic object id for deletion and queries purposes.

See event argument classes below:

using System;
namespace MyController
{
  public delegate void ClientEventHandler(object sender, ClientEventArgs e);
  public class ClientEventArgs : EventArgs
  {
  public long Id { get; set; }
  public string Name { get; set; }
  public string Registration { get; set; }
  }
}

using System;
namespace MyController
{
  public delegate void ObjectIdEventHandler &lt T &gt (object sender, ObjectIdEventArgs &lt T &gt e);
  public class ObjectIdEventArgs &lt T &gt : EventArgs
  {
    public T Id { get; set; }
  }
}


The controller will have a reference to a view (an interface) and it will access the view´s data fields for the client which is Id, Name and Registration.
Besides that, the controller will also be told to trigger actions by listening to the view´s events.
In this example, the service acts as if it was the model of the system.

using System;
using MyService;
namespace MyController
{
  public class ClientRegistrationController
  {
    private IClientRegistrationView View { get; set; }
    private ClientRegistrationService Service { get; set; }
    public ClientRegistrationController(IClientRegistrationView view)
    {
      View = view;
      View.InsertRequested += new ClientEventHandler(View_InsertRequested);
      View.UpdateRequested += new ClientEventHandler(View_UpdateRequested);
      View.RemoveRequested += new ObjectIdEventHandler &lt long &gt (View_RemoveRequested);
      View.RetrieveRequested += new ObjectIdEventHandler &lt long &gt (View_RetrieveRequested);
      Service = new ClientRegistrationService();   
    }
    void View_InsertRequested(object sender, ClientEventArgs e)
    {
      ClientDTO dto = new ClientDTO() { Id = e.Id, Name = e.Name, Registration = e.Registration };
      Service.Insert(dto);
      this.View.Id = dto.Id;
    }
    void View_UpdateRequested(object sender, ClientEventArgs e)
    {
      Service.Update(new ClientDTO() { Id = e.Id, Name = e.Name, Registration = e.Registration });
    }
    void View_RemoveRequested(object sender, ObjectIdEventArgs &lt long &gt e)
    {
      Service.Remove(e.Id);
    }
    void View_RetrieveRequested(object sender, ObjectIdEventArgs &lt long &gt e)
    {
      ClientDTO dto = Service.Retrieve(e.Id);
      this.View.Id = dto.Id;
      this.View.Name = dto.Name;
      this.View.Registration = dto.Registration;
    }
  }
}
As it can be seen above, the View doesn´t need to have a reference to the Controller. The view is totally decoupled form the controller but it can communicate with it by listening to the events.

2009-09-27

Extreme Programming Impressions

Whe I first read about XP Programming in 2002 ( http://www.extremeprogramming.org/ ) which is one of the agile methodologies for software development I didn't take it seriously.
At that time the authors of this methodology were saying that software didn´t need to be documented, models were not necessary or useful at all, people should be the documentation of the software, etc.
Immediately it came to my mind that it couldn´t work for many small (and big) software companies due to several problems:

– Software companies are constantly loosing and hiring workforce so how can they work if they keep loosing “documentation” which is on people´s minds ?

– How can they know the "what", "where" and "how" in the source code ?

Some years have passed and this methodology has matured and besides that other good methodologies of the same family like Scrum have come up too.
It called my attention that many state-of-art tech companies like Google and Yahoo! were working with Scrum and I started to get curious to know what it is about.

Five years later I decided to attend to a presentation about XP Programming in order to get a broader picture about it. It helped me to remove some miths I had such as the lack of documentation. Actually the Agile Methodology do not remove the activity of producing documentation but it just gave a different meaning for the documentation. The documentation should be provided if relevant for developers. It doesn´t have to include fancy diagrams but only the necessary information such as what is the system about, how to compile source-code, or other information that it is not self-explained in the system.

After reading "The Toyota Way" I noticed that agile methodologies was greatly inspired by this administration model. This model is basically driven to reduce waste, in other words, we should do only the necessary to accomplish our objectives, no more or no less. By reducing waste we are also reducing unnecessary work what can mean different things depending on our project such as no documentation, few documentation, no models, etc.

Therefore to be lean (and consequently agile), one must think on what tasks are been carried out and what tasks in the process should be eliminated if they have no value. Read the book above to have a good idea of the process.

2009-08-27

DynamicProxy: An Elegant Solution for Session/Transaction/Exception Management in NHibernate (or any other ORM)

Session management is a well solved problem for web applications and many detailed solutions can be found in the internet. The same is not true for winforms applications. Although there are solutions available in the internet, many of them are theoretical or just “complicated” for the medium programmer. Besides that it was difficult to find a solution (I have never found one) that could work for both web and winforms applications.

After a while (days), it came up to me the idea of using service proxies with Castle Dynamic Proxies. It turned out to be the easiest and cleanest approach I could think of because it has the ability to inject (aspects) behaviour around the service methods.

The idea can be coded in the following way:
  • Service classes with standard namespace and virtual methods


namespace Sample.Service
{
  public class SystemLogRegistrationService
  {
    public virtual void Modify(long codLogSistema)
    {
      SystemLog systemLog = Repository.Get().Load(codLogSistema);            
      systemLog.SetMachine = "MAQUINA" + DateTime.Now;
      systemLog.SetUserName = "PESSOA" + DateTime.Now;            
      systemLog.SetSystemName = "SISTEMA" + DateTime.Now;
      Repository.Get().Save(systemLog);            
    }
  }
}


Do not get distracted with the service code. The important thing to notice above is that the service does not contain anything else other than processing the domain classes (in this case, SystemLog). Also note that all service methods must be virtual. Without that, dynamic proxy won't work for these methods. The details of Repository implementation are out of the scope of this article and this subject is covered in enough details in several articles throughout the internet. (You can also send me a comment or email if you need information about that)

  • Usage Example


In order to make use of proxified services, one must create some kind of generator whose creation will be explained next. The ProxyGenerator below is a simple static class for didactic purposes that is responsible for dynamically generate proxies from a given type injecting the necessary aspects such as session/transaction management and exception handling or any other aspect you might think about.

SomeService serv = ProxyGenerator.InjectSessionTransactionExceptionAspects &lt SomeService &gt ();
serv.Modify(12048); // <= Modify method has session/transaction/exception management
  • Creating a proxy service factory
The proxy generator can be implemented using Castle Dynamic Proxy API.
using System;
using Castle.DynamicProxy;

namespace Sample.Persistence
{
  public static class ProxyGenerator 
  {
    private static ProxyGenerator _generator = new ProxyGenerator();        
    public static TService InjectSessionTransactionExceptionAspects &lt TService &gt ()
    {
      return (TService)_generator.CreateClassProxy(
        typeof(TService),
        new SessionTransactionExceptionAspect());    
    }
  }
}
  • An interceptor for the service class methods
using System;
using Castle.DynamicProxy;
using NHibernate;
using NHibernate.Context;

namespace Sample.Persistence
{
  /// 
  /// Intercepts service methods (must be virtual) and inject
  /// session / transaction and exception aspects
  /// 
  public class SessionTransactionExceptionAspect: IInterceptor
  {
    /// 
    /// Intercepts service methods and adds the following behaviors
    /// >>> Before executing a method:
    ///     * opens session
    ///     * begins transaction
    /// >>> After executing method:
    ///     * Commits transaction
    /// >>> In case there is exception
    ///     * Rollbacks transaction
    ///     * Handles exception
    /// >>> At the end
    ///     * Closes session
    /// 
    public object Intercept(IInvocation invocation, params object[] args)
    {
      object retorno = null;
      ITransaction tx = null;
      try
      {          
        CurrentSessionContext.Bind(SessionFactory.Instance.OpenSession());
        tx = SessionFactory.Instance.GetCurrentSession().BeginTransaction();
        retorno = invocation.Proceed(args);
        tx.Commit();
      }
      catch (Exception exception)
      {
        if (tx != null) { tx.Rollback(); }
          throw exception;
      }
      finally
      {
        ISession s = SessionFactory.Instance.GetCurrentSession();
        s.Close();
        CurrentSessionContext.Unbind(s.SessionFactory);
      }
      return retorno;
    }
  }
}
Above is the center of the whole idea. The interceptor class above captures only the service methods and ignores the rest. The following tasks are executed inside a try-catch-finally: (when it is a service method)
  • Session is created
  • Transaction is initialized
  • The method itself is executed
  • if method is ok, transaction is confirmed
  • if there is exception, transaction is cancelled and exception is handled
  • Finally session is closed

2009-08-21

Avoid "Tall" DAO Factories

A "tall" DAO factory can be defined as a big class that contains too much methods for each business class that compounds your domain model.

public class DAOFactory
{
IClass1DAO GetClass1DAO() { ... }
IClass2DAO GetClass2DAO() { ... }
IClass3DAO GetClass3DAO() { ... }
IClass4DAO GetClass4DAO() { ... }
IClass5DAO GetClass5DAO() { ... }
IClass6DAO GetClass6DAO() { ... }
IClass7DAO GetClass7DAO() { ... }
IClass8DAO GetClass8DAO() { ... }
IClass9DAO GetClass9DAO() { ... }
IClass10DAO GetClass10DAO() { ... }
: : : :
}


Besides big, these kind of class should be modified every time a new domain class is added to your system.
In order to avoid that to happen, one good option is to use a generic method for all DAO interfaces.

public class DAOFactory
{
ICommonDAO GetDAO < I > ( ) where I : ICommonDAO { ... }
}


The action of searching the corresponding DAO interface implementation can be easily achieved by using .NET reflection support for Assemblies and Types.

2009-06-13

Agile Modeling in Software Projects

Recently Jeff Sutherland mentioned another certification for software programmers since Scrum does not include software engineer techniques but very present in XP (extreme programming) management. That is probably the reason why many software developers work with Scrum and XP methodologies together.

However although XP is very software-programming oriented it is still not enough to have a good software design in large systems projects. Additionally in many organizations it is very difficult to find a product owner that fully understand the business rules and can manage the software functionalities.

In order to efficiently use Scrum, there must be someone responsible for understanding the business. If there is no product owner, one employee must be chosen to study and logically model the business. That is exactly why a good business modeling is imperative before any large software development.

Good software design and business understanding prevents or reduces significantly re-work tasks. It is considered wasted work since these tasks do not devliver anything useful to the client and often happens when developers did not captured well the business rules.

Thus the following software development process is proposed to match DDD and agile approach. In this software process, there can be product owners, developers and scrum masters just like original Scrum the difference is that before the sprints (see Scrum reference) can start, a long DDD session is necessary in order to produce a good business model.

Briefly describing the following steps should be taken:

  1. A selected person assumes the role of Product Owner
  2. Product Owner becomes responsible for studying and building a business model
  3. Product Owner writes all the system features using User Stories (from XP)
  4. Product Owner schedules a Planning Meeting with the Scrum Master and Developers to present User Stories and the Business Model
  5. Scrum Master schedules a Sprint Meeting with developers to plan the Next Sprint based on the Stories
  6. Developers begin the Sprint (from 1 to 2 weeks)
  7. Scrum Master Organizes Daily Meetings with Developers (just like Scrum)
  8. At the end of the Spring, Scrum Master schedules a Weekly Meeting to present the system to the Product Owner but it also includes the developers of the project who makes considerations about the system presented
  9. Scrum Master organized a Retrospective Meeting with the developers to discuss what went wrong or right with the Sprint and then they start planning the next Sprint.
  10. Go to Step 6 until Product Owner gets satisfied

2009-06-10

How the repository pattern works ?

The classes that represent the elements of a domain must contain all the business logic inside it such as tax calculation, name validation, etc. However in many circumstances it is also necessary to access data in order to complete the business logic inside these classes.

Take the example below:

Suppose I want to create an instance from the Client class and that clients must have a name and an address (there may be more information but lets stay with those two data for simplification purposes).
So, this could be instantiated like: (C# code)

// Open database connection (and Begin Transaction)
SessionManager.Open( );
: : :
// Parameters are: name, zipcode, adress number, address complement, country
Client client = new Client(“New Client”,”12500”,12,“Room 14”,Country.US);
: : :
// Close database connection (and Commit Transaction)
SessionManager.Close( );

Although simple, the line above hides many steps such as:
  • Check if client name is valid
  • Check if zipcode exists in the county US
  • Check if address number is correct
  • Check if addres complement id correct
  • Check if there are clients with the same name and address
  • Proceed with the client creation
However in order to complete some of this steps, the Client object should be able to access the data layer and that is the responsibility of the repositories. According to Martin Fowler's website: Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects.
Reference: http://www.martinfowler.com/eaaCatalog/repository.html

In order to make it possible the code line above, an Address and Client class must be implemented.

See full code listing below:

// Address is a value object used by Client class
public class Address
{
public Address(string zipCodeNumber,int number,string addrComplement)
{
// Check if zipcode number exists in the country (ZipCode Repository uses SessionManager inside it)
IZipCodeRepository zipCodeRepository = RepositoryManager.GetRepository( );
ZipCode zipCode = zipCodeRepository.Get(zipCodeNumber,country);
if (zipCode == null) { throw new NonExistentZipCodeException(zipCodeNumber,country);
// Check if address number is correct
if (number <= 0) { throw new InvalidAddressNumberException(number); }
// Check if address complement is correct
if (complement.Trim( ) == string.Empty) { throw new InvalidAddressComplementException(addrComplement)); }
// Sets values
this._zipCode = zipCode;
this._number = number;
this._complement = complement;
}
private ZipCode _zipCode = null;
public ZipCode ZipCode get { return _zipCode; }
private int _number = 0;
public int Number { get { return _number; } }
private string _complement = string.Empty;
public string Complement { get { return _complement; } }
}

// Now the Client class
public class Client
{
private long _id;
public long Id { get { return id; } set { this.id = value; } }
private string _name = string.Empty;
public Name
{
get { return _name; }
// Check if name is valid
set
{
if (name.Trim( ) == string.Empty) { throw new InvalidNameException(); }
// Check if there are Clients with same name and address
IClientRepository clientRepository = RepositoryManager.GetRepository();
bool exists = clientRepository.ClientExists(name,zipCodeNumber,number,addrComplement,country);
if (exists) { throw new ClientExistsException( ); }
this._name = value;

}
}
private Address _address;
public Address { get { return _address; } }
public Client(string name,string zipCodeNumber,int number,string addrComplement,Country country)
{
// Creates a Client
this.Address = new Address(zipCodeNumber,number,addrComplement,country);
this.Name = name;
}
}

Repositories have at least two advantages:
  • It removes data specific code from the domain classes which are concerned only about business logic
  • It allows unit tests since repositories are referred as interfaces in domain classes and thus fake repositories can be created without depend on database connection

2009-03-12

Using .NET Nullable Types with NHibernate 1.2

Originally, NHibernate 1.2 does not support nullable types from .NET such as DateTime?, int?, bool?, etc. but that can be solved by implementing specific NHibernate specific user types.
Not all nullable user types are listed for all .NET nullable types are listed below. But it can be easily done by following the example specially for numeric types.
However if you need help you jut send an email.

Nullable user types code listings:

NullableDateTimeType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableDateTimeType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          //object valor = NHibernateUtil.DateTime.NullSafeGet(rs, names[0]);
          object valor = null;
          if (rs[names[0]] != DBNull.Value)
              valor = Convert.ToDateTime(rs[names[0]]);

          DateTime? dateTime = null;

          if (valor != null)
          {
              dateTime = (DateTime)valor;
          }
          return dateTime;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.String.NullSafeSet(cmd, null, index);
          }
          else
          {
              DateTime? dateTime = (DateTime)value;
              NHibernateUtil.AnsiString.NullSafeSet(cmd, dateTime.Value.ToString("yyyy/MM/dd HH:mm:ss.fff"), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableBooleanType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableBooleanType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Boolean.NullSafeGet(rs, names[0]);
          bool? caracter = null;
          if (valor != null)
          {
              caracter = (bool)valor;
          }
          return caracter;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Boolean.NullSafeSet(cmd, null, index);
          }
          else
          {
              bool? caracter = (bool)value;
              NHibernateUtil.Boolean.NullSafeSet(cmd, caracter.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableCharType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using System.Data;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableCharType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Character.NullSafeGet(rs, names[0]);
          Char? caracter = null;
          if (valor != null)
          {
              caracter = (Char)valor;
          }
         return caracter;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {  
          if (value == null)
          {
               NHibernateUtil.Character.NullSafeSet(cmd, null, index);
          }
          else
          {
              Char? caracter = (Char)value;
              NHibernateUtil.Character.NullSafeSet(cmd, caracter.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableDecimalType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using System.Data;
using NHibernate.Util;
using NHibernate;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableDecimalType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Decimal.NullSafeGet(rs, names[0]);
          Decimal? inteiro = null;
          if (valor != null)
          {
              inteiro = (Decimal)valor;
          }
          return inteiro;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Decimal.NullSafeSet(cmd, null, index);
          }
          else
          {
              Decimal? inteiro = (Decimal)value;
              NHibernateUtil.Decimal.NullSafeSet(cmd, inteiro.Value.ToString().Replace(',','.'), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

NullableDoubleType.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using NHibernate;
using NHibernate.SqlTypes;
using System.Data;

namespace Utilitario.GerenciaDados
{
  public class NullableDoubleType : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Double.NullSafeGet(rs, names[0]);
          Double? valorD = null;
          if (valor != null)
          {
              valorD = (double)valor;
          }
          return valorD;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Double.NullSafeSet(cmd, null, index);
          }
          else
          {
              Double? valor = (Double)value;
              NHibernateUtil.Double.NullSafeSet(cmd, valor.Value.ToString().Replace(',','.'), index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}
NullableInt32Type.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NHibernate.UserTypes;
using System.Data;
using NHibernate.Util;
using NHibernate;
using NHibernate.SqlTypes;

namespace Utilitario.GerenciaDados
{
  public class NullableInt32Type : IUserType
  {
      #region IUserType Members
      public bool Equals(object x, object y)
      {
          return object.Equals(x, y);
      }
      public int GetHashCode(object x)
      {
          return x.GetHashCode();
      }
      public object NullSafeGet(IDataReader rs, string[] names, object owner)
      {
          object valor = NHibernateUtil.Int32.NullSafeGet(rs, names[0]);
          Int32? inteiro = null;
          if (valor != null)
          {
              inteiro = (Int32)valor;
          }
          return inteiro;
      }
      public void NullSafeSet(IDbCommand cmd, object value, int index)
      {
          if (value == null)
          {
              NHibernateUtil.Int32.NullSafeSet(cmd, null, index);
          }
          else
          {
              Int32? inteiro = (int)value;
              NHibernateUtil.Int32.NullSafeSet(cmd, inteiro.Value, index);
          }
      }
      public object DeepCopy(object value)
      {
          return value;
      }
      public object Replace(object original, object target, object owner)
      {
          return original;
      }
      public object Assemble(object cached, object owner)
      {
          return cached;
      }
      public object Disassemble(object value)
      {
          return value;
      }
      public SqlType[] SqlTypes
      {
          get { return new SqlType[] { new StringSqlType() }; }
      }
      public Type ReturnedType
      {
          get { return typeof(string); }
      }
      public bool IsMutable
      {
          get { return false; }
      }
      #endregion
  }
}

2008-12-26

Extremely Short Introduction for Ruby on Rails

Ruby on Rails

This file contains brief descriptions of a Ruby on Rails project.

Important Rails Commands

Here a list of the most relevant rails command-line programs organized by task:

  • Starting a Rails Project: rails

  • Executing a Rails Project: ruby script\server ( on application directory )

  • Generating a new Model: ruby script\generate model

  • Generating a new Controller: ruby script\generate controller


Directory Contents

app

Holds all the code that's specific to this particular application.

app/controllers

Holds controllers that should be named like weblogs_controller.rb for automated URL mapping. All controllers should descend from ApplicationController which itself descends from ActionController::Base.

app/models

Holds models that should be named like post.rb.

Most models will descend from ActiveRecord::Base.

app/views

Holds the template files for the view that should be named like weblogs/index.erb for the WeblogsController#index action. All views use eRuby syntax.

app/views/layouts

Holds the template files for layouts to be used with views. This models the common header/footer method of wrapping views. In your views, define a layout using the layout :default and create a file named default.erb. Inside default.erb, call <% yield %> to render the view using this layout.

app/helpers

Holds view helpers that should be named like weblogs_helper.rb. These are generated for you automatically when using script/generate for controllers. Helpers can be used to wrap functionality for your views into methods.

config

Configuration files for the Rails environment, the routing map, the database, and other dependencies.

db

Contains the database schema in schema.rb. db/migrate contains all the sequence of Migrations for your schema.

doc

This directory is where your application documentation will be stored when generated using rake doc:app

lib

Application specific libraries. Basically, any kind of custom code that doesn't belong under controllers, models, or helpers. This directory is in the load path.

public

The directory available for the web server. Contains subdirectories for images, stylesheets, and javascripts. Also contains the dispatchers and the default HTML files. This should be set as the DOCUMENT_ROOT of your web server.

script

Helper scripts for automation and generation.

test

Unit and functional tests along with fixtures. When using the script/generate scripts, template test files will be generated for you and placed in this directory.

vendor

External libraries that the application depends on. Also includes the plugins subdirectory. This directory is in the load path.

How does Model, View and Controller relate to each other ?

The application directory is structured like below:

app

|-controllers

|-models

|-views

The fastest way to generate a complete crud for a model is to generate a controller with the scaffold option:

> script/generate scaffold blog title:string content:text date_created:datetime

After understanding of ruby-on-rails it is considered better practice to generate models, views and controllers separately:

  • To generate a blog controller, one must type:

> script/generate controller blog

Result: a BlogController class will be generated at app/controllers in BlogController.rb

  • To generate a blog model, one must type:

> script/generate model blog

Result: a Blog class will be generated at app/model in blog.rb

  • views can not be generated, you have to go to app/views/blog and create a blog.html.erb.

Views for BlogController are automatically assigned in app/views/blog by name convention. ( Since BlogController will have a blog directory in app/views ).

Views in app/views/blog, must have a *.html.erb extension and an index.html.erb must be created for initial page. Other auxiliary pages can be created in the same directory with different names.

In order to add/remove/update models fields, one must only update the corresponding table in the data model only. After that the following command should be executed to update the models in Ruby-on-Rails:

> rake db:migrate