Documentation

Command Line Usage

Once the gem is installed the `serve` command will be available from the command prompt. To launch Serve, just type the command and press enter:

				
					serve
				
			

This will launch a simple web server which you can access from any web browser at the following address:

				
					http://localhost:4000
				
			

Once the server is going it will output a running log of its activity. To stop the server at any time, type CTRL+C at the command prompt. By default the serve command serves up files from the current directory. To change this behavior, `cd` to the appropriate directory before starting serve or pass the directory as the final parameter to the command:

				
					serve my-project
				
			

The `serve` command automatically binds to 0.0.0.0 (localhost) and uses port 4000 by default. To serve files over a different IP (that is bound to your computer) or port specify those options on the command line:

				
					serve 4000              # a custom port
serve 192.168.1.6        # a custom IP
serve 192.168.1.6:4000   # a custom IP and port
				
			

For your convenience if the file “script/server” exists in the current directory the serve command will start that instead of launching a Ruby Web server. You can specify the environment that you want to start the server with as an option on the command line:

				
					serve production         # start script/server in production mode
				
			

Creating a New Serve Project

For simple projects, you don’t need to structure your files in a specific way. All ERB, Haml, and Sass files will be processed wherever they are found in the project root. But for more complex projects you may want to use Serve with a `config.ru` file so that you can take advantage of other Rack middleware and structure the project in a Rack compatible way.

To create a new Rack-based Serve project in the "project" directory, type the following on the command line:

				
					serve create project   # create a new project in the project directory
				
			

This will create a new project with the following directory structure:

				
					project/
  |
  +-- config.ru              # Rack configuration file
  |
  +-- compass.config         # Compass configuration file
  |
  +-- public/                # Directories for static assets
  |    |
  |    +-- stylesheets/      # Compiled stylesheets
  |    |
  |    +-- images/
  |    |
  |    `-- javascripts/
  |
  +-- stylesheets/           # Sass and SCSS source files
  |    |
  |    `-- application.scss  # Example SCSS file for application
  |
  +-- tmp/                   # Needed for Passenger (mod_passenger)
  |    |
  |    `-- restart.txt
  |
  `-- views/                 # Store your ERB, Haml, etc. here
				
			

If you would like to generate the project with a specific JavaScript framework you can do so with the -j flag:

				
					serve create my-project -j prototype
				
			

Available frameworks are: jqueryjquery-uimootoolsprototype, and scriptaculous.

You can also specify a “template” to base your Serve project on with the -t flag.

				
					serve create my-project -t blank
				
			

A template can be one of the built-in templates (blank or default), or a directory of your choosing. Files in the template directory will overwrite the base files needed for an install.

The serve create command can be executed multiple times or on an existing project without negative consequences.

Exporting a Serve Project

To export your project, use the new "export" command:

				
					serve export project output
				
			

Where “project” is the path to the project and “output” is the path to the directory where you would like your HTML and CSS generated.

Please note! This feature is quite new. If you have problems exporting, please post about them on the GitHub issue tracker.

Converting a Compass Project to a Serve Project

If you are a Compass user you can convert an existing Compass project to a Serve project with the "convert" sub-command:

				
					serve convert mockups
				
			

This will rename and move a number of files for you and will turn your Compass project into a Serve project.

The convert command respects the same flags as the create command.

Note: After upgrading a Compass project, you will no longer need to use the compass watch command to generate your stylesheets. Your stylesheets will be compiled on the fly with Serve.

Understanding Layouts

In Serve layouts work a little differently than they do in Rails. Because there are no controllers to derive layout names from, Serve relies on the directory structure to determine the layout associated with a specific view. Serve layouts are stored in "_layout.erb" or "_layout.haml" files. Serve searches for a layout file in the same directory as the view. If it fails to find one there, it traverses up the directory tree searching each parent directory until it finds the "nearest" layout.

For example, assuming following directory structure:

				
					      views/
          |
  A)      +-- _layout.erb
          |
          +-- index.erb
          |
          `-- about/
                |
  B)            +-- _layout.erb
                |
                `-- index.erb
				
			

For “views/about/index.erb” Serve will use layout B. If layout B did not exist, Serve would go up the directory tree and discover layout A which it would use to render the view.

For “views/index.erb” Serve would immediately discover and use layout “A” because it is in the same directory.

So Serve searches up the directory tree for the nearest layout file, and uses that file to render the view. This is convenient because it allows you to structure your Serve project in a way that allows entire “branches” of to share the same layout and “branches” lower down can override the layout used.

Understanding Partials

Partials in Serve work much like they do in Rails. Prefix your partials with an underscore ("_") and use the render helper method in your views to render the partial:

				
					<%= render "footer" %>
				
			

Or,

				
					<%= render "/shared/footer" %>
				
			

View Helpers

If you drop a file called "view_helpers.rb" in your views directory, you can define custom helpers for your Haml and ERB views. Just create a ViewHelpers module and define your helper methods there:

				
					module ViewHelpers
  def custom_method
    "Request object: #{request.headers['user-agent']}"
  end
end
				
			

Helpers have full access to the request and response objects so you can easily read and manipulate headers or do other fancy tricks.

Serve provides a number of stock helpers to make it easier for you to prototype Rails applications:

				
					# Escape Helpers
html_escape(string)                  # escape HTML in string
h(string)                            # alias for html_escape
json_escape(string)                  # escape invalid JSON characters in string
j(string)                            # alias for json_escape

# Content Helpers
capture(&block)                      # Capture a block inside of a view or layout
content_for(symbol, &block)          # Capture a block and store it by symbol
content_for?(symbol)                 # Has content been captured for symbol?
get_content_for(symbol)              # Retrieve content for symbol (equivalent to `yield symbol`)
set_content_for(symbol, string)      # Set content for symbol to string

# Flash Helpers
flash                                # fake flash for request

# Param Helpers
params                               # access params for request
boolean_param(key)                   # retrieve value of a boolean param (true/false)

# Render Helpers
render(partial)                      # Render a partial

# Tag Helpers
content_tag(name, content, ...)      # a double HTML tag
tag(name, ...)                       # a single HTML tag
image_tag(src, ...)                  # an HTML image tag
image(name, ...)                     # shorthand for standard image tag
javascript_tag(...)                  # a javascript tag
link_to(name, href, ...)             # a link to name at href
link_to_function(name, ...)          # a link to a function
mail_to(email_address, ...)          # a mailto link
javascript_include_tag(*sources)     # Rails-style javascript tags for sources
stylesheet_link_tag(*sources)        # Rails-style stylesheet tags for sources
				
			

Template Engines & File Types

Serve does special processing for files with following extensions:

textile:Evaluates the document as Textile (requires the Redcloth gem)
markdown:Evaluates the document as Markdown (requires the Bluecloth gem)
erb:Evaluates the document as ERB
haml:Evaluates the document as Haml (requires the Haml gem)
slim:Evaluates the document using the Slim template language (requires the Slim gem)
sass:Evaluates the document as Sass (requires the Sass gem)
scss:Evaluates the document as SCSS (requires the Sass gem)
less:Evaluates the document as Less (requires the less gem)
email:Evaluates the document as if it is an e-mail message; the format is identical to a plain/text e-mail message’s source
redirect:Redirects to the URL contained on the last line of the file

Prototyping Rails Applications with Serve

This is tutorial is incomplete. Help us finish it!

Serve can be used as a rapid prototyping framework for Rails applications. It is designed to complement Rails development and enforce a strict separation of concerns between designer and developer. Using Serve with Rails allows the designer to happily work in their own space creating an HTML prototype of the application, while the developer works on the Rails application and copies over HTML from the prototype as needed. This allows the designer to focus on presentation and flow while the developer can focus on the implementation.

Let’s have a look at how it all works.

Installation

To get started we need to download and install the Ruby gem for Serve:

				
					$ sudo gem install serve
				
			

After we’ve done that it’s probably a good idea to install a couple of additional gems so that Serve will play nicely with Haml, Markdown, and Textile:

				
					$ sudo gem install haml sass BlueCloth RedCloth
				
			

Project Directory Structure

Once we have everything installed the next thing to do is setup the project directory. I like to setup my projects with the following directory structure:

artworkLogos and other identity design files go here
mockupsFireworks or Photoshop web app mockups go here
prototypeThe HTML prototype for the web app goes here
applicationThe actual Rails application is here

Let’s go ahead and setup the directory for the prototype. We’ll use the serve create command to create the initial prototype directory and files:

				
					$ serve create prototype
				
			

This should output something like this:

				
					create  prototype
create  prototype/public
create  prototype/tmp
create  prototype/views
create  prototype/config.ru
create  prototype/LICENSE
create  prototype/.gitignore
create  prototype/compass.config
create  prototype/README.markdown
create  prototype/public/images
create  prototype/public/javascripts
create  prototype/public/stylesheets
create  prototype/stylesheets
create  prototype/stylesheets/application.scss
create  prototype/views/_layout.html.erb
create  prototype/views/hello.html.erb
create  prototype/views/view_helpers.rb
create  prototype/views/index.redirect
				
			

You’ll note that the serve create command creates a directory structure that is somewhat similar to a Rails project:

				
					prototype/
  |
  +-- config.ru              # Rack configuration file
  |
  +-- compass.config         # Compass configuration file
  |
  +-- public/                # Directories for static assets
  |    |
  |    +-- stylesheets/      # Compiled stylesheets
  |    |
  |    +-- images/
  |    |
  |    `-- javascripts/
  |
  +-- stylesheets/           # Store Sass source files here
  |    |
  |    `-- application.scss  # Example SCSS file for application
  |
  +-- tmp/                   # Needed for Passenger (mod_passenger)
  |    |
  |    `-- restart.txt
  |
  `-- views/                 # Store your ERB, Haml, etc. here
       |
       +-- _layout.html.erb  # Example layout
       |
       +-- hello.html.erb    # Example view
       |
       `-- view_helpers.rb   # Example view helpers
				
			

Views and layouts for your prototype application belong in the “views” directory. The “public” directory is for static assets – resources like images or javascripts that don’t need server side processing. The “stylehseets” directory is the place where you should store Sass source files (if you use those). Serve will automatically compile Sass and SCSS files stored here into public/stylesheets directory.

Creating Our First Screen

Now that we have the prototype directory set up, let’s create our first page so that you can get a feel for how Serve works. This will be a simple HTML login page for our application.

In the “views” directory, create a file named “login.html.erb” and insert the following source code:

				
					<form action="/dashboard/" method="put">
  <p>
    <label for="username">Username</label>
    <input type="text" name="username" id="username" />
  </p>
  <p>
    <label for="password">Password</label>
    <input type="password" name="password" id="password" />
  </p>
  <p>
    <input type="submit" value="Login" />
  </p>
</form>
				
			

Starting Serve

To view our login page in a Web browser, we need to start up Serve in the directory where we are building the prototype:

				
					% cd prototype
% serve
[2008-02-23 15:19:05] INFO  WEBrick 1.3.1
[2008-02-23 15:19:05] INFO  ruby 1.8.6 (2007-09-24) [universal-darwin9.0]
[2008-02-23 15:19:05] INFO  Serve::Server#start: pid=5087 port=4000
...
				
			

Once you execute the serve command it will launch a mini Web server for the prototype and will output a noisy log of any activity. (To stop the command at any point simply switch back to the command line and press Ctrl+C.)

By default the serve command automatically serves files from the directory that it is started in over port 4000 on your local machine. To access the the prototype in your Web browser go to:

				
					http://localhost:4000
				
			

Now navigate to the following URL:

				
					http://localhost:4000/login
				
			

You should see the contents of the login page. Note that Serve allows you to refer to pages without their extension. This allows you to use URLs in your documents that correspond to the URLs that Rails uses by default.

Layouts

One thing to note about the source that I gave you for the login page. I intentionally left out the <html>, <head>, and <body> tags because they belong in a layout—not a view file. Let’s go ahead and define that layout now.

Replace the contents of the file named “_layout.html.erb” in the “views” directory of your prototype with the following:

				
					<html>
  <head>
    <title><%= @title %></title>
  </head>
  <body>
    <h1><%= @title %></h1>
    <%= yield %>
  </body>
</html>
				
			

This layout includes a small amount of ERB. ERB stands for Embedded Ruby. ERB allows you to embed Ruby code into a web page to dynamically render content. In our case, we are using it in the layout to indicate the title of the web page and to insert the content of the page at the appropriate point. You can use ERB in layout or view files.

Embedded Ruby is delineated with the opening and closing sequence <% and %> respectively. Sequences that begin with an addition equals sign insert their output directly into the HTML. In this case we want to render the @title variable as the title in the head and as the first heading in the document body. The yield keyword is used to insert the content of the page at that point.

We need to make one small change to our login page before continuing. Insert the following line at the top of login.html.erb file:

				
					<% @title = "Login" %>
				
			

This will set the @title variable for the login page. Now, switch back to your Web browser and navigate to:

				
					http://localhost:4000/login
				
			

Content regions with content_for

Let’s add a sidebar to the login page. To do this in a layout friendly way, we will use the content_for helper method to define the sidebar.

Add the following code to the bottom of login.html.erb:

The page should now have a title and heading that both read “Login”.

				
					<% content_for :sidebar do %>
  <h3>New Around Here?</h3>
  <p>No problem! Just <a href="/signup/">create an account</a>.</p>
<% end %>

				
			

This defines a new content region of the page that we can render wherever we want in the layout. The :sidebar symbol defines the name of the content region.

Now to modify the layout to work with this new content region. In “_layout.html.erb” replace the code:

				
					<h1><%= @title %></h1>
<%= yield %>
				
			

With the following:

				
					<div id="content">
  <h1><%= @title %></h1>
  <%= yield %>
</div>
<div id="sidebar">
  <%= yield :sidebar %>
</div>
				
			

This defines two new divs for the content and sidebar portions of the document. The first call to yield renders the content portion of a view (everything apart from regions defined by calls to content_for). The second call to yield passes the name of our content region as a symbol. When yield is called with a symbol, it renders the associated content region. In our case yield :sidebar causes Serve to render the content that we defined for the :sidebar region at that point in the layout.

Now add a block for inline styles to the “head” of the layout:

				
					<style>
  #content { float: left;  width: 60%; }
  #sidebar { float: right; width: 40%; }
</style>
				
			

We could certainly put this in it’s own file (in the public/stylesheets directory), but for the purposes of this demonstration, it works just as well in the head of the document.

The full layout file should now look like this:

				
					<html>
  <head>
    <title><%= @title %></title>
    <styles>
       #content { float: left;  width: 60%; }
       #sidebar { float: right; width: 40%; }
     </styles>
  </head>
  <body>
    <div id="content">
      <h1><%= @title %></h1>
      <%= yield %>
    </div>
    <div id="sidebar">
      <%= yield :sidebar %>
    </div>
  </body>
</html>
				
			

Now switch back to your Web browser at:

				
					http://localhost:4000/login
				
			

And check out the new multi-column layout on the login page.

Partials

Let's add a header and a footer our page now. To keep everything self-contained, we can define the header and footer in separate files and include them into the main layout.

Create a file in the views directory called "_header.html.erb" and insert the following code:

				
					<div id="header">
  My Web App
</div>

				
			

Create another file in the views directory called “_footer.html.erb” and insert the following code:

				
					<div id="footer">
  Copyright © 2022, My Company. All rights reserved.
</div>
				
			

Now switch over to “_layout.html.erb” and insert this line just after the opening <body> tag:

				
					<%= render 'header' %>
				
			

And this this line, just before the closing </body> tag:

				
					<%= render 'footer' %>
				
			

What we’ve done here is added two calls to the render helper method. One for the header and one for the footer. Partials, like layouts, are prefixed with an “_”, but when you refer to them inside of a view or layout, drop the “_” and the file extension. This is why we were able to write render 'header' instead of render '_header.html.erb'. Both variations will actually work, but the first is preferred because it’s more concise.

To pretty things up a bit, let’s add a couple of additional styles in the head portion of the layout. Insert the following code inside the twin <style> tags:

				
					#header { background: #666; color: white; font-size: 120%; padding: 10px; }
#footer { clear: both; color: #333; }
				
			

Your “_layout.html.erb” file should now look like this:

				
					<html>
  <head>
    <title><%= @title %></title>
    <style>
       #content { float: left;  width: 60%; }
       #sidebar { float: right; width: 40%; }
       #header { background: #666; color: white; font-size: 120%; padding: 10px; }
       #footer { clear: both; color: #333; }
     </style>
  </head>
  <body>
    <%= render 'header' %>
    <div id="content">
      <h1><%= @title %></h1>
      <%= yield %>
    </div>
    <div id="sidebar">
      <%= yield :sidebar %>
    </div>
    <%= render 'footer' %>
  </body>
</html>
				
			

Now switch back to your Web browser at:

				
					http://localhost:4000/login
				
			

And check out the new header and footer that we’ve added.

View Helpers

We can

view_helpers.rb

This tutorial is incomplete. Help us finish it!

Using Coffee Script with Serve

  1. Add the “rack-coffee” gem to your Gemfile

  2. Add these lines to your config.ru file:

				
					module ViewHelpers
  def custom_method
    "Request object: #{request.headers['user-agent']}"
  end
end
				
			
  1. Run bundle in your project folder.

Now you can put your .coffee files in /javascripts and link to them as usual (replacing .coffee with .js). For example, the URL for /javascripts/test.coffee is /javascripts/test.js.

Сopyright © 2024 get-serve.com. Serve is open-source software. It is completely free for commercial and non-commercial use. Wanna help?