Socket
Book a DemoInstallSign in
Socket

sinatra-chassis

Package Overview
Dependencies
Maintainers
1
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

sinatra-chassis

1.1.1
bundlerRubygems
Version published
Maintainers
1
Created
Source

Chassis

Chassis is a mutable framework extension for Sinatra that's designed to help you focus on less code by writing less code.

It starts by generating a basic Sinatra application, bootstrapped to run on Rack. As your application grows, Chassis will adapt itself to your changes. You choose the gems, design patterns, scope, and size of your application.

Focus only on what you use, and forget the rest.

jarrodtaylor.github.io/sinatra-chassis

Getting Started

Prerequisites

  • A working Ruby installation: ruby-lang.org
  • Experience with Sinatra: sinatrarb.com

Installation

Install Chassis as a RubyGem:

~: gem install sinatra-chassis

Generating an Application

The Chassis gem comes with a cli for generating ready-to-run applications:

~: chassis
The chassis command creates a new chassis app. 

Usage:
  chassis [options] app_path 

Example:
  chassis -g -h ~/Projects/my_app 

Options:
  -g, --git            Init a git repo, add the first commit
  -h, --heroku         Create a Heroku app
      --skip-bundle    Don't run bundle install
  -e, --extension      Create a Chassis extension

The chassis command will generate a boilerplate application and bundle it's gems. Adding -g will initialize a git repo and add the first commit. Adding -h will create and link to an app on Heroku. Adding --skip-bundle will skip over the gem bundling step. And -e will generate a Chassis extension template.

The -g and -h switches assume git and the heroku toolbelt to already be installed.

Create a new application and take a look around:

~: chassis SampleApp
~: cd SampleApp

--

What's Included

app.rb

Hooks together all the pieces of the application:

  • Requires the gems in Gemfile.lock
  • Requires the Chassis helpers
  • Requires sinatra/reloader in development
  • Enables sessions and sets a session_secret
  • Requires the default load path
  • Adds a sample route
config.ru

Loads app.rb on a Rack server.

/tmp/restart.txt

Used to restart the application on a Rack server.

/public

For storing publicly accessible files, such as JavaScripts and Stylesheets, as well as:

  • /public/robots.txt for handling web crawlers
  • /public/favicon.ico for adding a favicon to browser bookmarks and address bars
Gemfile and Gemfile.lock

For managing gems.

/views/layout.erb

A stock HTML5 template with alert and yield methods already in the body.

Rakefile

Loads app.rb, the Chassis rake tasks, rake tasks from the loaded extensions, and all your own .rake scripts from /tasks.

.gitignore

For keeping unnecessary files out of your git repository.

README.md

A place to put instructions for using your application.

Running on Localhost

Chassis is based on a standard Sinatra application, and runs the same way:

~/SampleApp: ruby app.rb

Your application is now running at localhost:4567.

Use Ctrl-C to stop the local server.

The Basics

Loading Your Application

Your application structure is defined in app.rb with the require_directory method, allowing you to organize your application code into multiple files and load them in the proper order.

require_directory([
  'config',
  'settings',
  'modules',
  'helpers',
  'libraries',
  'models',
  'controllers',
  'routes'
])

require_directory will require all the Ruby scripts from each directory it's passed, and you can add your own directory structure to the Array.

Adding Route Handlers

Namespaced routes and tests can be generated with the rake task sinatra:add:routes[namespace]. The [namespace] argument is required.

~/SampleApp: rake sinatra:add:routes[users]
# => add ./routes/users.rb
# => add ./tests/routes/users_tests.rb

CoffeeScript and Sass

CoffeeScript and Sass files in the /public directory will be automatically compiled when requested. Just link to them as if linking to a .js or .css file:

<head>
  <!-- Compile and load /public/js/global.coffee -->
  <script type="text/javascript" src="/js/global.js"></script>

  <!-- Compile and load /public/css/theme.scss -->
  <link rel="stylesheet" type="text/css" href="/css/theme.css">
</head>

Notice the .js and .css extensions. If a .js or .css file exists in the same directory and with the same name as a .coffee or .scss file, the .js or .css file will be loaded. This allows assets to be precompiled without changing the script and link tags.

Precompiling

Compiling CoffeeScript and Sass is generally too slow to be good practice on a production server. The solution is to work with .coffee and .scss during development, then precompile them into .js and .css for deployment.

The task rake assets:precompile will compile all .coffee and .scss files in /public into .js and .css files of the same name.

~/SampleApp: rake assets:precompile

Web servers will see the .js and .css files first, bypassing the .coffee and .scss files completely.

Precompiled assets are automatically minified.

If you need to use "bare" CoffeeScript, just set Tilt::CoffeeScriptTemplate.default_bare to true. On-the-fly and precompiled .coffee files will the compiled as bare JavaScript.

Adding assets:precompile to your deploy scripts will automate this process, as well as keep compiled files out of source control.

Heroku already does this by default, it works with their read-only filesystem.

The task rake assets:decompile will remove the compiled .js and .css files.

~/SampleApp: rake assets:decompile

Assets Path

By default, Chassis uses /public for .coffee and .scss files. To use other directories, add them to the assets_path setting:

set :assets_path, ['public', 'scripts']
<head>
  <!-- Compile and load /scripts/global.coffee -->
  <script type="text/javascript" src="/scripts/global.js"></script>
</head>

All .coffee and .scss files will be moved to /public when precompiled.

Mobile Templates

In cases where responsive design just won't work, Chassis can find mobile view templates and layouts. Prefix your view template extension with .mobile and it will be sent to mobile devices only.

For example: hello_world.erb would have the mobile counterpart hello_world.mobile.erb, and layout.haml would have the mobile counterpart layout.mobile.haml.

To enable mobile templates, use the mobile_views setting:

enable :mobile_views

Mobile devices are determined by their user agents, which are listed as an Array of regular expressions in the mobile_user_agents setting. The default setting applies to iPhone and Android devices, but you're free to override it:

set :mobile_user_agents, [/iPhone/, /Android.*AppleWebKit/]

Catch-all Route Handling

Sinatra evaluates all the routes in your application and returns a 404 Not Found error if it doesn't find a match. Chassis intercepts this error and looks in the /views directory for a directory/template combination that matches the request path before passing the request to an error page.

For example: A request for /hello/world will first look for the route handler get('/hello/world'). If the route handler doesn't exist, it will then look for the template /views/hello/world.erb. If the template doesn't exits, it will raise a 404 Not Found error.

The template extension/rendering engine doesn't matter: /views/hello/world.erb will work just as well as /views/hello/world.haml.

To disable catch-all route handling:

disable :catch_all_route

Production Error Pages

No production application should be without well styled error pages. Chassis adds a basic error page, only shown when running in production.

To use a your own custom error page, create the view template /views/error.erb. Chassis makes the error available to the template with the variables code and message:

<h1>Error <%= code %></h1>
<hr />
<h2><%= message %></h2>

Note that when your application is running in development mode, you'll still see the usual Sinatra error pages.

Running Tests

Any test scripts in /tests can be run with the rake task chassis:test[file]:

~/SampleApp: rake chassis:test[routes/users_tests]

Leaving out the [file] argument will run everything in /tests:

~/SampleApp: rake chassis:test

Adding Rake Tasks

In addition to the Chassis rake tasks, any .rake files you add to the /tasks directory will automatically be available.

Interactive Ruby Shell

To load your application in an IRB session:

~/SampleApp: rake chassis:irb
irb(main):001:0> settings.catch_all_route
=> true
irb(main):002:0> exit

Helpers

Chassis comes with a few Sinatra helpers to speed up coding of commonly reused elements.

To compare links with the current URL, use the active helper:

<a href="/hello/world" class="<%= active('hello') %>">Hi</a>
# => <a href="/hello/world" class="active">Hi</a>
<a href="/goodbye/world" class="<%= active('goodbye') %>">Bye</a>
# => <a href="/goodbye/world" class="">Bye</a>

Style a.active links in your CSS for "sticky" links.

Alerting Users

The alert helper uses rack-flash to send one-time messages to users:

get '/send/message/?'
  flash[:alert] = 'This is a public service announcement.'
  redirect '/hello/world'
end
<%= alert %>
# => <div id='alert'>This is a public service announcement.</div>

Flash empties itself after each request, so your message will only display once.

Date Selects

The date_select helper, when combined with the Sinatra time_for helper, makes converting dates to and from DateTime objects for a database simple:

<form>
  <%= date_select(DateTime.now,
        select_class: 'updated_at',
           select_id: 'updated_at',
         select_name: 'updated_at',
          start_year: 1999,
            end_year: 2021,
           day_first: true,
          month_name: false) %>
</form>

A valid DateTime object is the only required argument. The others are recommended:

select_name: name attribute for fields, appended with _day, _month, or _year

select_id: id attribute for fields, appended with _day, _month, or _year

select_class: class attribute for fields

start_year: first year to use in year select (default: 3 years ago)

end_year: last year to use in year select (default: 3 years from now)

day_first: true/false to show the day before the month (default: false)

month_name: true/false to display month names (default: false)

For easy site-wide styling, generated select fields always have the classes month_select, day_select, and year_select.

To convert back to a DateTime object, use the time_for Sinatra helper on the submitted form fields:

time_for("#{params[:dob_year]}-#{params[:dob_month]}-#{params[:dob_day]}")

Hiding Elements

When it's necessary to hide elements based on Ruby conditionals:

<div style="<%= hidden unless @user.recent? %>">Hello, world!</div>
# => <div style="display: none;">Hello, world!</div>

Numerability

Ruby uses duck typing, but incompatible types are still incompatible. To find out if a String can be used as a Number:

numeric?('1')
# => true
numeric?('hello')
# => false

Titles

Titleizing a String will uppercase the first letter of each word:

titleize('hello world')
# => 'Hello World'

Truncation

The truncate helper will truncate both Strings and Numbers:

truncate('Lorem ipsum dolor sit amet.', word_count: 3, end_string: '...')
# => 'Lorem ipsum dolor...'
truncate(1.234000, decimal: 1)
# => 1.2
truncate(1.234000, decimal: 5)
# => 1.234
truncate(1.234000, decimal: 5, trailing_zeros: true)
# => '1.23400'

truncate() will try to round numbers by default. For simple truncation, pass round: false.

Extensions

Chassis can be easily extended to work with other gems, databases, APIs, design patterns, etc. Extensions are packaged as gems, and included in your Gemfile. Example:

gem 'chassis-datamapper'

Running bundle install after adding an extension gem will make that it available to your app.

Some gems will include a setup rake task to help get things started. Be sure to check out your newly available tasks for each extension with rake -T.

Commonly Used Extensions

Writing Your Own

If you're familiar with writing RubyGems, you can create your own extensions:

chassis -e my_extension

The generated extension includes placeholders to fill in your own code, tasks, and templates.

More Info

Check out the wiki for more info.

License

Copyright (C) 2013 Jarrod Taylor.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

FAQs

Package last updated on 20 Jul 2013

Did you know?

Socket

Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.

Install

Related posts

SocketSocket SOC 2 Logo

Product

About

Packages

Stay in touch

Get open source security insights delivered straight into your inbox.

  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc

U.S. Patent No. 12,346,443 & 12,314,394. Other pending.