This blog post is intended as a guideline on how to set up a basic MVC (Model-View-Controller) structure in ruby using ERB, Sinatra and Active Record.
MVC is a best-practice pattern used in software systems. One of the benefits is that it can avoid spaghetti code structures and help ease maintenance (or avoid coders such as Irv from the strip below)
You can apply MVC to a basic ‘Hello World’ app by following the next steps (and according to a logical folder structure!):
Model: Represent data and logic by creating a ruby Class which interacts with an SQLite database via Active Record for storing and retrieving the “Hello Message”.
View: Use ERB to render the “Hello Message” to be displayed to the user.
Controller: Use Sinatra routes to ask the Model for the “Hello Message” and to send this back to the browser for user display.
Build initial folder structure
Start by creating the following basic folder structure. The Models, Views and Controllers will be grouped into a folder named ‘app’. The ‘config’ folder will contain the environment configurations and the ‘db’ folder will contain the database (Active Record) migrations (i.e. create ‘Hello World’ table).
Setup environment and gems
Add the files ‘Gemfile’ and ‘config.ru’ to the root of the project folder.
Add the file ‘environment.rb’ to the config folder.
Add the file ‘Rakefile’ to the root of the project folder.
Add the following code to these files. Make sure to run command ‘bundle’ at the end.
Add the file ‘hello.rb’ to the models folder: contains a Hello class which inherits from ActiveRecord Base.
Add the file ‘create_hello.rb’ to the migrate folder: contains the code to create the database schema. For this example, a table named ‘hello’ will be created with a column ‘message’ to hold the “Hello World!” message. Make sure to run the rake task db:migrate to create the table.
Add the file ‘hello_controller.rb’ to the controllers folder: code in this file ensures that a new instance of Hello is created and persisted with a message “Hello World!”. This message is then passed to ERB (Embedded Ruby) for rendering in the index template.