<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Riley Thompson on Medium]]></title>
        <description><![CDATA[Stories by Riley Thompson on Medium]]></description>
        <link>https://medium.com/@rileythompson?source=rss-d5cde03b2709------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*l06X1NFt79-CNiX5.</url>
            <title>Stories by Riley Thompson on Medium</title>
            <link>https://medium.com/@rileythompson?source=rss-d5cde03b2709------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 19:40:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rileythompson/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Making a Simple Blog App in Sinatra]]></title>
            <link>https://medium.com/@rileythompson/setting-up-a-simple-sinatra-blog-app-db56dda4c280?source=rss-d5cde03b2709------2</link>
            <guid isPermaLink="false">https://medium.com/p/db56dda4c280</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[sinatra]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Riley Thompson]]></dc:creator>
            <pubDate>Wed, 07 Jun 2017 01:39:25 GMT</pubDate>
            <atom:updated>2017-06-30T15:36:17.807Z</atom:updated>
            <content:encoded><![CDATA[<p>Sinatra is a light and simple web framework that can be useful when you just want to get something up and running really quickly without all the bloat that Rails provides.</p><p>This article will focus on configuring a brand new Sinatra application using a PostgresSQL database, and RSpec for our testing suite in a Unix environment. We will then give the user the ability visit a page and create a blog post.</p><p>Let’s begin!</p><p>Open your command-line and let’s create a directory for our new App.</p><pre>mkdir sinatra_practice</pre><p>and then</p><pre>cd sinatra_practice</pre><p>Now we have an empty project directory to fill with Sinatra goodness, let’s give it some initial structure. As a rails-centric dev I like keeping everything related to our App in an app folder, and all configurations in a config folder.</p><pre>mkdir app</pre><pre>mkdir config</pre><p>Lets also add a Gemfile so we can describe our dependencies for this app:</p><p>At the root of the app (right under your sinatra_practice directory)</p><pre>touch Gemfile</pre><h3>Gems</h3><p>Now that we have a place to put them, let’s talk about the required gems.</p><p><a href="https://github.com/rack/rack">Rack</a> — Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby.</p><p><a href="https://github.com/sinatra/sinatra">Sinatra</a> — (The Magic) This gives us access to the Sinatra Domain Specific Language to aide us in our web development.</p><p><a href="https://rubygems.org/gems/pg/versions/0.18.4">Pg</a> — This is a ruby interface for our soon to be Postgres Database.</p><p><a href="https://github.com/rails/rails/tree/master/activerecord">Active Record</a> — This is an object relational mapping tool. With some inheritance from ActiveRecord::Base this connects our classes (models) to our Postgres tables.</p><p><a href="https://github.com/janko-m/sinatra-activerecord">Sinatra Active Record </a>— Gives us some extra helper methods including some rake tasks for dealing with an SQL database.</p><p><a href="https://github.com/rtomayko/shotgun">Shotgun </a>— This is an automatic reloading version of the rackup command that’s shipped with Rack. Meaning you can alter code in your server, and have it live without needing to restart it.</p><p><a href="https://github.com/cldwalker/tux">Tux </a>— This is an interactive console. Similar to running rails c/rails console in a rails project. You can interact with your models/helpers, and also display your app’s route’s and settings.</p><p><a href="https://github.com/rspec/rspec">RSpec</a> — DSL used for our test-driven development. This is used in conjunction with Capybara (below) to conduct feature tests.</p><p><a href="https://github.com/teamcapybara/capybara">Capybara</a> —Yet another DSL (what qualifies something to be a DSL? It uses method calls and passes args without parentheses, SO expressive!!) which allows you to conduct feature/functional tests by simulating a real user interacting with your web page.</p><p><a href="https://github.com/DatabaseCleaner/database_cleaner">Database Cleaner</a> — We will use this to manage our test database before it runs, while it runs, and after it runs.</p><p>Your Gemfile should now look something like this:</p><p>We add a source at the top so our file knows where to look for these precious gems. Notice that we have moved all of our test-related gems into a test group which means these gems are only available in our test-environment.</p><pre>source “<a href="https://rubygems.org/">https://rubygems.org</a>&quot;</pre><pre>gem “rack”<br>gem “sinatra”<br>gem “activesupport”<br>gem “pg”<br>gem “activerecord”<br>gem “sinatra-activerecord”<br>gem “tux”<br>gem “shotgun”</pre><pre>group :test do<br> gem “capybara”<br> gem “database_cleaner”<br> gem “rspec”<br> gem “rack-test”<br>end</pre><p>Now run bundle in the command line to install your gems.</p><h3>Rakefile</h3><p>Now it’s time for a Rakefile to set up any jobs you may want, and to have a place to require all of those handy rake tasks that our sinatra-activerecord gem gave us.</p><p>In your App’s root directory</p><pre>touch Rakefile</pre><p>And add the following code in your new Rakefile</p><pre>require “bundler”<br>Bundler.require</pre><pre>require “sinatra/activerecord/rake”</pre><p>Bundler.require loops over each gem in your Gemfileand requires all gem entries for use in your Rake tasks.</p><h3>Database</h3><p>Now let’s get our App connected to a database. In sinatra_practice/config</p><p>touch database.rb</p><p>Inside database.rb add the following:</p><pre># set the database based on the current environment<br>database_name = “sinatra-practice-#{SinatraPracticeApp.environment}”<br>db = URI.parse(ENV[‘DATABASE_URL’] || “postgres://localhost/#{database_name}”)</pre><pre># connect ActiveRecord with the current database<br>ActiveRecord::Base.establish_connection(<br> :adapter =&gt; db.scheme == ‘postgres’ ? ‘postgresql’ : db.scheme,<br> :host =&gt; db.host,<br> :port =&gt; db.port,<br> :username =&gt; db.user,<br> :password =&gt; db.password,<br> :database =&gt; “#{database_name}”,<br> :encoding =&gt; ‘utf8’<br>)</pre><p>As the comment suggests, this will decide which database to connect to based on what the SinatraPracticeApp.environment method call returns.</p><p>Again, in sinatra_practice/config touch database.yml, and add the following:</p><pre>development:<br> adapter: postgresql<br> database: sinatra-practice-development</pre><pre>test:<br> adapter: postgresql<br> database: sinatra-practice-test</pre><pre>production:<br> adapter: postgresql<br> database: sinatra-practice-production</pre><p>Again (last time I promise), in sinatra_practice/config touch environment.rb, and add the following:</p><pre>require ‘bundler’<br>Bundler.require</pre><pre># get the path of the root of the app<br>APP_ROOT = File.expand_path(“..”, __dir__)</pre><pre># require the controller(s)<br>Dir.glob(File.join(APP_ROOT, ‘app’, ‘controllers’, ‘*.rb’)).each { |file| require file }</pre><pre># require the model(s)<br>Dir.glob(File.join(APP_ROOT, ‘app’, ‘models’, ‘*.rb’)).each { |file| require file }</pre><pre># require database configurations<br>require File.join(APP_ROOT, ‘config’, ‘database’)</pre><pre># configure SinatraPractice settings<br>class SinatraPracticeApp &lt; Sinatra::Base<br> set :method_override, true<br> set :root, APP_ROOT<br> set :views, File.join(APP_ROOT, “app”, “views”)<br> set :public_folder, File.join(APP_ROOT, “app”, “public”)<br>end</pre><p>Now in your command line run our rake task rake db:create you should see something similar to this as a response after:</p><pre>Created database ‘sinatra-practice-development’</pre><pre>Created database ‘sinatra-practice-test</pre><p>Cool! Our app is officially connected to a database.</p><h3>File Structure</h3><p>Let’s talk about this code from our config/environment.rb :</p><pre>require ‘bundler’<br>Bundler.require</pre><pre># get the path of the root of the app<br>APP_ROOT = File.expand_path(“..”, __dir__)</pre><pre># require the controller(s)<br>Dir.glob(File.join(APP_ROOT, ‘app’, ‘controllers’, ‘*.rb’)).each { |file| require file }</pre><pre># require the model(s)<br>Dir.glob(File.join(APP_ROOT, ‘app’, ‘models’, ‘*.rb’)).each { |file| require file }</pre><pre># require database configurations<br>require File.join(APP_ROOT, ‘config’, ‘database’)</pre><pre># configure SinatraPractice settings<br>class SinatraPracticeApp &lt; Sinatra::Base<br> set :method_override, true<br> set :root, APP_ROOT<br> set :views, File.join(APP_ROOT, “app”, “views”)<br> set :public_folder, File.join(APP_ROOT, “app”, “public”)<br>end</pre><p>This is doing a lot for us, but it also expects us to structure our application with a classic <a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC</a> style. This will require all of our written code for our app as long as we have the correct file structure. So, let’s set that up.</p><p>You can see the constant at the top which is set to APP_ROOT, notice it goes one level up from the current path config/environment.rb to our root path for sinatra_practice_app. Now that we have a root we can begin to access our entire file structure by joining different locations with our app root and requiring them iteratively given the correct folders are there.</p><p>From the root of your app.</p><pre>mkdir app/controllers app/models  app/views</pre><p>and also, mkdir db at the root of your app so we have a place to store the schema and any future migrations.</p><p>Sweet! Our file structure should be looking pretty good at this point.</p><h3>TDD</h3><p>Let’s get RSpec and Database cleaner configured.</p><p>If you don’t remember waaaaay up at the top, RSpec is what we will use to define the behavior we expect from our app, and DatabaseCleaner will help keep our database in tip-top shape while it does so.</p><p>We can initialize RSpec in for project. The following command should create an .rspec and a spec/spec_helper.rb file.</p><pre>bundle <strong>exec </strong>rspec --init</pre><p>In your new spec_helper file add the following code:</p><pre>ENV[&quot;RACK_ENV&quot;] ||= &quot;test&quot;</pre><pre>require File.expand_path(&quot;../../config/environment&quot;, __FILE__)<br>require &#39;rspec&#39;<br>require &#39;capybara/dsl&#39;<br>require &#39;database_cleaner&#39;</pre><pre>Capybara.app = SinatraPracticeApp</pre><pre>DatabaseCleaner.strategy = :truncation</pre><pre>RSpec.configure do |c|<br>  c.include Capybara::DSL</pre><pre>c.before(:all) do<br>    DatabaseCleaner.clean<br>  end</pre><pre>c.after(:each) do<br>    DatabaseCleaner.clean<br>  end<br>end</pre><p>This configures RSpec with Capybara as well as DatabaseCleaner. Currently Database Cleaner will empty our test data base each time before our test suite is ran, and it will also clean it after each test. There are several different configurations for Database Cleaner which you can find <a href="https://github.com/DatabaseCleaner/database_cleaner"><strong>here</strong></a>.</p><p>Run rspec . You should now get a response similar to this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/818/1*9tk5X3nf74ZMRiqGMmkWKw.png" /></figure><p>Cool! We can start our TDD process.</p><p><em>disclaimer: Due to the simplicity of the app I will not be showing you how to set up the </em><a href="https://github.com/thoughtbot/factory_girl"><em>FactoryGirl</em></a><em> gem, but if your app is of any significant size you should check it out as it saves tons of time building out Models for your tests.</em></p><p>Let’s write a feature test to build out our blog creation functionality.</p><p>mkdir spec/features &amp;&amp; touch spec/features/user_can_create_a_blog_spec.rb</p><p>Yes, that’s one command ^.</p><p>Inside user_can_create_a_blog_spec.rb add the following:</p><pre>require ‘spec_helper’</pre><pre>RSpec.describe “User can post a blog” do<br> it “when filling in all information” do</pre><pre>   visit “/”</pre><pre>   fill_in “blog[title]”, with: “Test”<br>   fill_in “blog[content]”, with: “This is my new blog.”</pre><pre>   click_on “Post”<br>   new_blog = Blog.last</pre><pre>   expect(new_blog.title).to eq(&quot;Test&quot;)<br>   expect(new_blog.content).to eq(&quot;This is my new blog&quot;)<br>   expect(current_path).to eq(“/blogs/#{new_blog.id}”)</pre><pre>   expect(page).to have_content(“This is my new blog.”)<br>   expect(page).to have_content(“Test”)<br> end<br>end</pre><p>Feel free to veer off course, but for simplicities sake the user will fill in a form at the root of our application, and then be redirected to blog show page if the blog persists to the database.</p><p>Let’s run RSpec to see where we’re at:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I8TwL5wc5iTbdDpZOY8e2w.png" /><figcaption><strong>It FAILS, good that’s what we want to see.</strong></figcaption></figure><p>It’s complaining about an uninitialized constant called SinatraPracticeApp</p><p>Remember our configuration for that class SinatraPracticeAppin config/environment.rb ? Let’s put that to use:</p><p>In app/controllers touch sinatra_practice_app.rb</p><p>This will be our bread and butter file, unlike Rails this file will act to define both our routes and our controller actions.</p><p>Add the following code in your new app file:</p><pre>class SinatraPracticeApp &lt; Sinatra::Base</pre><pre>end</pre><p>Run RSpec again:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YICDiZucl0JgjAlOhNqUBw.png" /><figcaption>Nice! Capybara is visiting our root page, but can’t find our form field.</figcaption></figure><p>Let’s create it!</p><p>mkdir app/views/blogs &amp;&amp; touch app/views/blogs/new.erb</p><p>Don’t forget to add a layout as well so we have full html structure.</p><p>touch app/views/layout.erb and add the following:</p><pre>&lt;!DOCTYPE html&gt;<br>&lt;html&gt;<br> &lt;head&gt;<br> &lt;title&gt;Sinatra Practice&lt;/title&gt;<br> &lt;/head&gt;<br> &lt;body&gt;<br> &lt;%= yield %&gt;<br> &lt;/body&gt;<br>&lt;/html&gt;</pre><p>Open up your new.erb file and add the following:</p><pre>&lt;h1&gt;Post your blog!&lt;/h1&gt;</pre><pre>&lt;form class=”blog-form” action=”/” method=”post”&gt;<br> &lt;input type=”text” name=”blog[title]” placeholder=”Enter your blog’s title…”&gt;&lt;br&gt;<br> &lt;textarea name=”blog[content]” rows=”8&quot; cols=”80&quot;&gt;&lt;/textarea&gt;<br> &lt;input type=”submit” value=”Post”&gt;<br>&lt;/form&gt;</pre><p>How does our App know to send us to this new.erb view? Well, it doesn’t let’s do that.</p><p>app/controllers/sinatra_practice_app.rb add the following:</p><pre>get ‘/’ do<br>  erb :”blogs/new”<br>end</pre><p>This tells our application that when it receives a GET request at the root of our application or ‘/’ to route our user to our new.erb view we just created.</p><p>You guessed it, run rspec again.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3pxvJdw_RTmGkT4RnwuEJg.png" /><figcaption>A new failure! Amazing, so our test is visiting our web page and found our form, but it doesn’t know what a blog is.</figcaption></figure><p>Let’s create it.</p><p>In your command line run rake db:create_migration NAME=create_blogs</p><p>You should now have a new migration file in db/migrate , in that file, add the following:</p><pre>class CreateBlogs &lt; ActiveRecord::Migration[5.1]<br>  def change<br>    create_table :blogs do |t|<br>    t.string :title<br>    t.text :content<br>    t.timestamps null: false<br>    end<br>  end<br>end</pre><p>Then run rake rake db:migrate , you should see the table created in the command line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xcdCbsNI9do1L4S2br8UeQ.png" /></figure><p>So, we have our migration created, but what about our model?</p><p>touch app/models/blog.rb and inside add the following:</p><pre>class Blog &lt; ActiveRecord::Base</pre><pre>end</pre><p>Our model class inherits from ActiveRecord base to use AR’s ORM functionality.</p><p>Run rspec</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_PdyeVxOTSORZt9lkstYog.png" /><figcaption>So our new_blog is returning nil class now. Maybe that’s because we haven’t told our app how to create it!</figcaption></figure><p>Let’s do it</p><p>Following RESTful principles our form is submitting our data with a POST verb. Let’s create a route to receive that.</p><p>In your app file add:</p><pre>post ‘/’ do<br> blog = Blog.new(params[“blog”])<br> if blog.save<br>   redirect “/blogs/#{blog.id}”<br> else<br>   erb :”blogs/new”<br> end<br>end</pre><p>This tells our app that when receiving a post to the ‘/’ route to create a new post from the params passed in. Notice the params method call, calling params[“blog”] returns a hash of the data including the title and content. Passing that hash into a Blog.new call will initialize an item with those attributes since they correspond with attributes defined in the database.</p><p>We then check if blog is able to save (this is more of a validation check, of which we have none for this project, but it is a good habit) and redirect to a show page so the user can see it, otherwise we render the page form again.</p><p>Run rspec</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ad_cSo4WmQxD0SqjTkYXig.png" /><figcaption>Nice! New error. So we don’t see “This is my new blog.” it seems our redirect to the show page isn’t working.</figcaption></figure><p>Let’s fix it!</p><p>Add the following to your app file:</p><pre>get ‘/blogs/:id’ do<br>  <a href="http://twitter.com/blog">@blog</a> = Blog.find(params[:id])<br>  erb :”blogs/show”<br>end</pre><p>This gives us a route with a placeholder for the id. When this action is hit, we then find the associated blog by the id param passed in, and render our show view. Let’s create that view!</p><p>app/views/blogs/show.erb and add the following:</p><pre>&lt;h1&gt; &lt;%= @blog.title %&gt; &lt;/h1&gt;</pre><pre>&lt;p&gt; &lt;%= @blog.content %&gt;&lt;/p&gt;</pre><p>This is accessing the instance variable we defined in our controller which should be equal to the corresponding blog it found. We then display the title and content using html tags and erb.</p><p>…. run rspec</p><p>One last step so you can access your server locally.</p><p>To run our app we need a config.ru file.</p><p>In the root of your app touch config.ru and add the following:</p><pre>require ‘bundler’<br>Bundler.require</pre><pre>$LOAD_PATH.unshift(File.expand_path(“app”, __dir__))</pre><pre>require File.expand_path(‘../config/environment’, __FILE__)</pre><pre>run SinatraPracticeApp</pre><p>Now run shotgun (remember our shotgun gem?) this looks in your config.ru and boots up your server.</p><p>Visit <a href="http://localhost:9292/">http://localhost:9292/</a> and you should see your new app!</p><p>Congratulations your tests should be passing, and you’ve just created a VERY simple blog app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db56dda4c280" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>