Scroll to top

After creating a content management system (CMS) basic structure, and the actual server using Go and Node.js, you’re ready to try your hand at another language. 

This time, I'm using the Ruby language to create the server. I have found that by creating the same program in multiple languages, you begin to get new insights on better ways to implement the program. You also see more ways to add functionality to the program. Let’s get started.

Setup and Loading the Libraries

To program in Ruby, you will need to have the latest version installed on your system. Many operating systems come pre-installed with Ruby these days (Linux and OS X), but they usually have an older version. This tutorial assumes that you have Ruby version 2.4.

The easiest way to upgrade to the latest version of ruby is to use RVM. To install RVM on Linux or Mac OS X, type the following in a terminal:

1
gpg --keyserver hkp://keys.gnupg.net --recv-keys 409B6B1796C275462A1703113804BB82D39DC0E3
2
curl -sSL https://get.rvm.io | bash -s stable

This will create a secure connection to download and install RVM. This installs the latest stable release of Ruby as well. You will have to reload your shell to finish the installation.

For Windows, you can download the Windows Ruby Installer. Currently, this package is up to Ruby 2.2.2, which is fine to run the libraries and scripts in this tutorial.

Once the Ruby language is properly installed, you can now install the libraries. Ruby, just like Go and Node, has a package manager for installing third-party libraries. In the terminal, type the following:

1
gem install sinatra
2
gem install ruby-handlebars
3
gem install kramdown
4
gem install slim

This installs the Sinatra, Ruby Handlebars, Kramdown, and Slim libraries. Sinatra is a web application framework. Ruby Handlebars implements the Handlebars templating engine in Ruby. Kramdown is a Markdown to HTML converter. Slim is a Jade work-alike library, but it doesn’t include Jade’s macro definitions. Therefore, the macros used in the News and Blog post indexes are now normal Jade.

Creating the rubyPress.rb File

In the top directory, create the file rubyPress.rb and add the following code. I will comment about each section as it's added to the file.

1
#

2
# Load the Libraries.

3
#

4
require 'sinatra'			# http://www.sinatrarb.com/

5
require 'ruby-handlebars' 	# https://github.com/vincent-psarga/ruby-handlebars

6
require 'kramdown' 			# http://kramdown.gettalong.org

7
require 'slim' 				# http://slim-lang.com/

8
require 'json'
9
require 'date'

The first thing to do is to load the libraries. Unlike with Node.js, these are not loaded into a variable. Ruby libraries add their functions to the program scope.

1
#

2
# Setup the Handlebars engine.

3
#

4
$hbs = Handlebars::Handlebars.new
5
6
#

7
# HandleBars Helper:   date

8
#

9
# Description:         This helper returns the current date

10
#                      based on the format given.

11
#

12
$hbs.register_helper('date') {|context, format|
13
	now = Date.today
14
	now.strftime(format)
15
}
16
17
#

18
# HandleBars Helper:   cdate

19
#

20
# Description:         This helper returns the given date

21
#                      based on the format given.

22
#

23
$hbs.register_helper('cdate') {|context, date, format|
24
	day = Date.parse(date)
25
	day.strftime(format)
26
}
27
28
#

29
# HandleBars Helper:   save

30
#

31
# Description:         This helper expects a

32
#                      "|" where the name

33
#                      is saved with the value for future

34
#                      expansions. It also returns the

35
#                      value directly.

36
#

37
$hbs.register_helper('save') {|context, name, text|
38
	#

39
	# If the text parameter isn't there, then it is the 

40
	# goPress format all combined into the name. Split it 

41
	# out. The parameters are not String objects. 

42
	# Therefore, they need converted first.

43
	#

44
	name = String.try_convert(name)
45
	if name.count("|") > 0
46
		parts = name.split('|')
47
		name = parts[0]
48
		text = parts[1]
49
	end
50
51
	#

52
	# Register the new helper.

53
	#

54
	$hbs.register_helper(name) {|context, value|
55
		text
56
	}
57
58
	#

59
	# Return the text.

60
	#

61
	text
62
}

The Handlebars library gets initialized with the different helper functions defined. The helper functions defined are date, cdate, and save

The date helper function takes the current date and time, and formats it according to the format string passed to the helper. cdate is similar except for passing the date first. The save helper allows you to specify a name and value. It creates a new helper with the name name and passes back the value. This allows you to create variables that are specified once and affect many locations. This function also takes the Go version, which expects a string with the name, ‘|’ as a separator, and value.

1
#

2
# Load Server Data.

3
#

4
$parts = {}
5
$parts = JSON.parse(File.read './server.json')
6
$styleDir = Dir.getwd + '/themes/styling/' + $parts['CurrentStyling']
7
$layoutDir = Dir.getwd + '/themes/layouts/' + $parts['CurrentLayout']
8
9
#

10
# Load the layouts and styles defaults.

11
#

12
$parts["layout"] = File.read $layoutDir + '/template.html'
13
$parts["404"] = File.read $styleDir + '/404.html'
14
$parts["footer"] = File.read $styleDir + '/footer.html'
15
$parts["header"] = File.read $styleDir + '/header.html'
16
$parts["sidebar"] = File.read $styleDir + '/sidebar.html'
17
18
#

19
# Load all the page parts in the parts directory.

20
#

21
Dir.entries($parts["Sitebase"] + '/parts/').select {|f|
22
	if !File.directory? f
23
		$parts[File.basename(f, ".*")] = File.read $parts["Sitebase"] + '/parts/' + f
24
	end
25
}
26
27
#

28
# Setup server defaults:

29
#

30
port = $parts["ServerAddress"].split(":")[2]
31
set :port, port

The next part of the code is for loading the cacheable items of the web site. This is everything in the styles and layout for your theme, and the items in the parts sub-directory. A global variable, $parts, is first loaded from the server.json file. That information is then used to load the proper items for the layout and theme specified. The Handlebars template engine uses this information to fill out the templates.

1
#

2
# Define the routes for the CMS.

3
#

4
get '/' do
5
  page "main"
6
end
7
8
get '/favicon.ico', :provides => 'ico' do
9
	File.read "#{$parts['Sitebase']}/images/favicon.ico"
10
end
11
12
get '/stylesheets.css', :provides => 'css'  do
13
	File.read "#{$parts["Sitebase"]}/css/final/final.css"
14
end
15
16
get '/scripts.js', :provides => 'js'  do
17
	File.read "#{$parts["Sitebase"]}/js/final/final.js"
18
end
19
20
get '/images/:image', :provides => 'image' do
21
	File.read "#{$parts['Sitebase']}/images/#{parms['image']}"
22
end
23
24
get '/posts/blogs/:blog' do
25
	post 'blogs', params['blog'], 'index'
26
end
27
28
get '/posts/blogs/:blog/:post' do
29
	post 'blogs', params['blog'], params['post']
30
end
31
32
get '/posts/news/:news' do
33
	post 'news', params['news'], 'index'
34
end
35
36
get '/posts/news/:news/:post' do
37
	post 'news', params['news'], params['post']
38
end
39
40
get '/:page' do
41
	page params['page']
42
end

The next section contains the definitions for all the routes. Sinatra is a complete REST compliant server. But for this CMS, I will only use the get verb. Each route takes the items from the route to pass to the functions for producing the correct page. In Sinatra, a name preceded by a colon specifies a section of the route to pass to the route handler. These items are in a params hash table.

1
#

2
# Various functions used in the making of the server:

3
#

4
5
#

6
# Function:    page

7
#

8
# Description: This function is for processing a page

9
#              in the CMS.

10
#

11
# Inputs:

12
# 				pg 	The page name to lookup

13
#

14
def page(pg)
15
	processPage $parts["layout"], "#{$parts["Sitebase"]}/pages/#{pg}"
16
end

The page function gets the name of a page from the route and passes the layout in the $parts variable along with the full path to the page file needed for the function processPage. The processPage function takes this information and creates the proper page, which it then returns. In Ruby, the output of the last function is the return value for the function.

1
#

2
# Function:    post

3
#

4
# Description: This function is for processing a post type

5
#              page in the CMS. All blog and news pages are

6
#    				post type pages.

7
#

8
# Inputs:

9
#              type   The type of the post

10
#              cat    The category of the post (blog, news)

11
#              post   The actual page of the post

12
#

13
def post(type, cat, post)
14
	processPage $parts["layout"], "#{$parts["Sitebase"]}/posts/#{type}/#{cat}/#{post}"
15
end

The post function is just like the page function, except that it works for all post type pages. This function expects the post type, post category, and the post itself. These will create the address for the correct page to display.

1
#

2
# Function:    figurePage

3
#

4
# Description: This function is to figure out the page

5
#              type (ie: markdown, HTML, jade, etc), read

6
#              the contents, and translate it to HTML.

7
#

8
# Inputs:

9
#              page      The address of the page 

10
#                        without its extension.

11
#

12
def figurePage(page)
13
	result = ""
14
15
	if File.exist? page + ".html"
16
		#

17
		# It's an HTML file.

18
		#

19
		result = File.read page + ".html"
20
	elsif File.exist? page + ".md"
21
		#

22
		# It's a markdown file.

23
		#

24
		result = Kramdown::Document.new(File.read page + ".md").to_html
25
26
		#

27
		# Fix the fancy quotes from Kramdown. It kills

28
		# the Handlebars parser.

29
		#

30
		result.gsub!("“","\"")
31
		result.gsub!("”","\"")
32
	elsif File.exist? page + ".amber"
33
		#

34
		# It's a jade file. Slim doesn't support

35
		# macros. Therefore, not as powerful as straight jade.

36
		# Also, we have to render any Handlebars first

37
		# since the Slim engine dies on them.

38
		#

39
		File.write("./tmp.txt",$hbs.compile(File.read page + ".amber").call($parts))
40
		result = Slim::Template.new("./tmp.txt").render()
41
	else
42
		#

43
		# Doesn't exist. Give the 404 page.

44
		#

45
		result = $parts["404"]
46
	end
47
48
	#

49
	# Return the results.

50
	#

51
	return result
52
end

The figurePage function uses the processPage function to read the page content from the file system. This function receives the complete path to the file without the extension. figurePage then tests for a file with the given name with the html extension for reading an HTML file. The second choice is for a md extension for a Markdown file. 

Lastly, it checks for an amber extension for a Jade file. Remember: Amber is the name of the library for processing Jade syntax files in Go. I kept it the same for inter-functionality. An HTML file is simply passed back, while all Markdown and Jade files get converted to HTML before passing back.

If a file isn’t found, the user will receive the 404 page. This way, your “page not found” page looks just like any other page except for the contents.

1
#

2
# Function:    processPage

3
#

4
# Description: The function processes a page by getting

5
#              its contents, combining with all the page

6
#              parts using Handlebars, and processing the

7
#              shortcodes.

8
#

9
# Inputs:

10
#              layout  The layout structure for the page

11
#              page    The complete path to the desired

12
#                      page without its extension.

13
#

14
def processPage(layout, page)
15
	#

16
	# Get the page contents and name.

17
	#

18
	$parts["content"] = figurePage page
19
	$parts["PageName"] = File.basename page
20
21
	#

22
	# Run the page through Handlebars engine.

23
	#

24
	begin
25
		pageHB = $hbs.compile(layout).call($parts)
26
	rescue
27
		pageHB = "

28
Render Error

29


30
"
31
	end
32
33
	#

34
	# Run the page through the shortcodes processor.

35
	#

36
	pageSH = processShortCodes pageHB
37
38
	#

39
	# Run the page through the Handlebar engine again.

40
	#

41
	begin
42
		pageFinal = $hbs.compile(pageSH).call($parts)
43
	rescue
44
		pageFinal = "

45
Render Error

46


47
" + pageSH
48
	end
49
50
	#

51
	# Return the results.

52
	#

53
	return pageFinal
54
end

The processPage function performs all the template expansions on the page data. It starts by calling the figurePage function to get the page’s contents. It then processes the layout passed to it with Handlebars to expand the template. 

Then the processShortCode function will find and process all the shortcodes in the page. The results are then passed to Handlebars for a second time to process any macros left by the shortcodes. The user receives the final results.

1
#

2
# Function:    processShortCodes

3
#

4
# Description: This function takes the page and processes

5
#              all of the shortcodes in the page.

6
#

7
# Inputs:

8
#              page     The contents of the page to 

9
#                       process.

10
#

11
def processShortCodes(page)
12
	#

13
	# Initialize the result variable for returning.

14
	#

15
	result = ""
16
17
	#

18
	# Find the first shortcode

19
	#

20
	scregFind = /\-\[([^\]]*)\]\-/
21
	match1 = scregFind.match(page)
22
	if match1 != nil
23
		#

24
		# We found one! get the text before it

25
		# into the result variable and initialize

26
		# the name, param, and contents variables.

27
		#

28
		name = ""
29
		param = ""
30
		contents = ""
31
		nameLine = match1[1]
32
		loc1 = scregFind =~ page
33
		result = page[0, loc1]
34
35
		#

36
		# Separate out the nameLine into a shortcode

37
		# name and parameters.

38
		#

39
		match2 = /(\w+)(.*)*/.match(nameLine)
40
		if match2.length == 2
41
			#

42
			# Just a name was found.

43
			#

44
			name = match2[1]
45
		else
46
			#

47
			# A name and parameter were found.

48
			#

49
			name = match2[1]
50
			param = match2[2]
51
		end
52
53
		#

54
		# Find the closing shortcode

55
		#

56
		rest = page[loc1+match1[0].length, page.length]
57
		regEnd = Regexp.new("\\-\\[\\/#{name}\\]\\-")
58
		match3 = regEnd.match(rest)
59
		if match3 != nil
60
			#

61
			# Get the contents the tags enclose.

62
			#

63
			loc2 = regEnd =~ rest
64
			contents = rest[0, loc2]
65
66
			#

67
			# Search the contents for shortcodes.

68
			#

69
			contents = processShortCodes(contents)
70
71
			#

72
			# If the shortcode exists, run it and include

73
			# the results. Otherwise, add the contents to

74
			# the result.

75
			#

76
			if $shortcodes.include?(name)
77
				result += $shortcodes[name].call(param, contents)
78
			else
79
				result += contents
80
			end
81
82
			#

83
			# process the shortcodes in the rest of the

84
			# page.

85
			#

86
			rest = rest[loc2 + match3[0].length, page.length]
87
			result += processShortCodes(rest)
88
		else
89
			#

90
			# There wasn't a closure. Therefore, just 

91
			# send the page back.

92
			#

93
			result = page
94
		end
95
	else
96
		#

97
		# No shortcodes. Just return the page.

98
		#

99
		result = page
100
	end
101
102
	return result
103
end

The processShortCodes function takes the text given, finds each shortcode, and runs the specified shortcode with the arguments and contents of the shortcode. I use the shortcode routine to process the contents for shortcodes as well.

A shortcode is an HTML-like tag that uses -[ and ]- to delimit the opening tag and -[/ and ]- the closing tag. The opening tag contains the parameters for the shortcode as well. Therefore, an example shortcode would be:

1
-[box]-
2
This is inside a box.
3
-[/box]-

This shortcode defines the box shortcode without any parameters with the contents of <p>This is inside a box.</p>. The box shortcode wraps the contents in the appropriate HTML to produce a box around the text with the text centered in the box. If you later want to change how the box is rendered, you only have to change the definition of the shortcode. This saves a lot of work.

1
#

2
# Data Structure:  $shortcodes

3
#

4
# Description:     This data structure contains all

5
#                  the valid shortcodes names and the

6
#                  function. All shortcodes should

7
#                  receive the arguments and the

8
#                  that the shortcode encompasses.

9
#

10
$shortcodes = {
11
	"box" => lambda { |args, contents|
12
		return("#{contents}")
13
	},
14
   'Column1'=> lambda { |args, contents|
15
		return("#{contents}")
16
   },
17
   'Column2' => lambda { |args, contents|
18
      return("#{contents}")
19
   },
20
   'Column1of3' => lambda { |args, contents|
21
      return("#{contents}")
22
   },
23
   'Column2of3' => lambda { |args, contents|
24
      return("#{contents}")
25
   },
26
   'Column3of3' => lambda { |args, contents|
27
      return("#{contents}")
28
   },
29
   'php' => lambda { |args, contents|
30
      return("#{contents}")
31
   },
32
   'js' => lambda { |args, contents|
33
      return("#{contents}")
34
   },
35
	"html" => lambda { |args, contents|
36
		return("#{contents}")
37
	},
38
   'css' => lambda {|args, contents|
39
      return("#{contents}")
40
   }
41
}

The last thing in the file is the $shortcodes hash table containing the shortcode routines. These are simple shortcodes, but you can create other shortcodes to be as complex as you want. 

All shortcodes have to accept two parameters: args and contents. These strings contain the parameters of the shortcode and the contents the shortcodes surround. Since the shortcodes are inside a hash table, I used a lambda function to define them. A lambda function is a function without a name. The only way to run these functions is from the hash array.

Running the Server

Once you have created the rubyPress.rb file with the above contents, you can run the server with:

1
ruby rubyPress.rb

Since the Sinatra framework works with the Ruby on Rails Rack structure, you can use Pow to run the server. Pow will set up your system’s host files for running your server locally the same as it would from a hosted site. You can install Pow with Powder using the following commands in the command line:

1
gem install powder
2
powder install

Powder is a command-line routine for managing Pow sites on your computer. To get Pow to see your site, you have to create a soft link to your project directory in the ~/.pow directory. If the server is in the /Users/test/Documents/rubyPress directory, you would execute the following commands:

1
cd ~/.pow
2
ln -s /Users/test/Documents/rubyPress rubyPress

The ln -s creates a soft link to the directory specified first, with the name specified secondly. Pow will then set up a domain on your system with the name of the soft link. In the above example, going to the web site http://rubyPress.dev in the browser will load the page from the server.

To start the server, type the following after creating the soft link:

1
powder start

To reload the server after making some code changes, type the following:

1
powder restart
rubyPress Main PagerubyPress Main PagerubyPress Main Page
rubyPress Main Page

Going to the website in the browser will result in the above picture. Pow will set up the site at http://rubyPress.dev. No matter which method you use to launch the site, you will see the same resulting page.

Conclusion

Well, you have done it. Another CMS, but this time in Ruby. This version is the shortest version of all the CMSs created in this series. Experiment with the code and see how you can extend this basic framework.

Did you find this post useful?
Want a weekly email summary?
Subscribe below and we’ll send you a weekly email summary of all new Code tutorials. Never miss out on learning about the next big thing.
Looking for something to help kick start your next project?
Envato Market has a range of items for sale to help get you started.