About
Rails conventions in Rust: generators, Active Record-style models, migrations, jobs, mailers and browser tests, on SQLite or Postgres.
Data & AnalyticsWhat you can do
- Active Record: #[nails::model], validations, callbacks, transactions, has_many, has_one, through, polymorphic associations and includes.
- Controllers and routes: resources, strong params, before_action, respond_to, flash, and signed and encrypted cookies.
- Views: Jinja templates with Rails helper names: link_to, form_with, content_for, partials and JSON views.
- Generators: scaffold, model, migration, controller, job, mailer, script, system_test and authentication.
Measured star growth
- in 24h
- Collecting history
- in 7 days
- Collecting history
- in 15 days
- Collecting history
- in 1 month
- Collecting history
Net star changes over overlapping periods, not daily totals. Missing measurements are left blank. Stars measure attention, not software quality.
README.md
OriginalIf you know Rails, you already know most of Nails. nails new,
nails g scaffold, db:migrate, fixtures and system tests work the way you
expect, with the same names and the same app layout. Your models and
controllers are plain synchronous Rust, with no .await.
#[nails::model]
#[derive(Debug, Clone, Default)]
#[has_many(Comment, dependent = destroy)]
pub struct Post {
pub id: i64,
pub title: String,
pub published: bool,
pub created_at: DateTime,
pub updated_at: DateTime,
}
let posts = Post::where_eq("published", true).order("created_at DESC").load()?;
[!NOTE] Nails is young and built by one person. Use it for side projects, not production yet. Missing pieces are tracked in the Rails parity issues.
Quick start
You need a Rust toolchain. Install the CLI from a checkout of this repo:
git clone https://github.com/wesleygrimes/nails
cd nails
cargo install --path crates/nails-cli
Generated apps depend on this checkout by path, so keep it where it is. Set
NAILS_PATH to use a different copy.
Then make an app:
nails new blog
cd blog
nails generate scaffold Post title:string body:text published:boolean
nails db:migrate
nails server # http://localhost:3000/posts
Run nails with no arguments to list every command.
What nails new makes
The same layout as a Rails app, with Rust files where Rails has Ruby. Here it
is after nails g scaffold Post title:string:
blog/
├── Cargo.toml
├── app/
│ ├── controllers/
│ │ ├── mod.rs
│ │ └── posts_controller.rs
│ ├── jobs/mod.rs
│ ├── mailers/mod.rs
│ ├── models/
│ │ ├── mod.rs
│ │ └── post.rs
│ └── views/
│ ├── layouts/
│ │ ├── application.html.jinja
│ │ ├── mailer.html.jinja
│ │ └── mailer.text.jinja
│ └── posts/
│ ├── _form.html.jinja
│ ├── _post.html.jinja
│ ├── _post.json.jinja
│ ├── edit.html.jinja
│ ├── index.html.jinja
│ ├── index.json.jinja
│ ├── new.html.jinja
│ ├── show.html.jinja
│ └── show.json.jinja
├── config/
│ ├── credentials.yml.enc
│ ├── database.yml
│ ├── master.key # git-ignored
│ └── routes.rs
├── db/
│ ├── migrate/
│ │ ├── 20261201195110_create_posts.rs
│ │ └── mod.rs # rewritten by the generators
│ ├── schema.sql # written by db:migrate
│ └── seeds.rs
├── public/ # 404.html, 500.html, robots.txt, assets/
├── src/
│ ├── lib.rs # the Application: routes, migrations, jobs
│ └── main.rs # the binary behind `nails server`, `db:*`, ...
├── test/
│ ├── controllers/posts_controller_test.rs
│ ├── fixtures/posts.yml
│ ├── jobs/mod.rs
│ ├── models/post_test.rs
│ ├── main.rs
│ └── test_helper.rs
├── log/ storage/ tmp/
└── README.md
Features
- Active Record:
#[nails::model], validations, callbacks, transactions,has_many,has_one,through, polymorphic associations andincludes. - Controllers and routes:
resources, strong params,before_action,respond_to, flash, and signed and encrypted cookies. - Views: Jinja templates with Rails helper names:
link_to,form_with,content_for, partials and JSON views. - Generators:
scaffold,model,migration,controller,job,mailer,script,system_testandauthentication. - Jobs and mail:
perform_later, retries, continuations, concurrency limits, tracked batches, recurring schedules (config/recurring.yml), multi-pool workers (config/queue.yml),RecordRef, mailers withdeliver_later, and a mail preview at/nails/mailsin development. - Testing: fixtures, integration tests,
assert_select, and system tests in headless Chrome. - Databases: SQLite by default, Postgres with
-d postgresql. - Dev tools: a server that rebuilds on save and shows compile errors in
the browser, plus
console,runner,dbconsoleand encrypted credentials.
Under the hood it's axum and tokio for HTTP, and minijinja for views.
A short tour
The code below is what the generators write, plus a few lines added by hand.
Models
A model is a struct with #[nails::model]. The table is the plural of the
struct name. Associations are attributes; validations go in Validations.
use nails::prelude::*;
#[nails::model]
#[derive(Debug, Clone, Default)]
#[has_many(Comment, dependent = destroy)]
pub struct Post {
pub id: i64,
pub title: String,
pub body: String,
pub published: bool,
pub created_at: DateTime,
pub updated_at: DateTime,
}
impl Validations for Post {
fn validate(&self, errors: &mut Errors) {
errors.validates_presence_of("title", &self.title);
}
}
#[nails::model]
#[derive(Debug, Clone, Default)]
pub struct Comment {
pub id: i64,
#[belongs_to(Post)]
pub post_id: i64,
pub body: String,
pub created_at: DateTime,
pub updated_at: DateTime,
}
That gives you post.comments(), comment.post(), Post::find(id),
Post::where_eq("title", "x").order("created_at DESC").load() and the rest.
Controllers and routes
Controllers implement Controller. This is the scaffold's create:
fn create(c: &mut Ctx) -> Result<Response> {
let mut post = Post::new(&post_params(c)?);
match post.save() {
Ok(()) => c.respond_to(
|c| {
c.flash("notice", "Post was successfully created.");
c.redirect_to(c.path_for("post", &post))
},
|c| {
let location = c.url_for("post", &post);
Ok(c.render_status("show", 201, context! { post })?.location(&location))
},
),
Err(Error::RecordInvalid(errors)) => c.respond_to(
|c| c.render_status("new", 422, context! { post, errors }),
|c| c.render_json(422, &errors.as_json()),
),
Err(e) => Err(e),
}
}
// Only allow a list of trusted parameters through.
fn post_params(c: &Ctx) -> Result<Params> {
c.params().expect("post", &["title", "body", "published"])
}
Routes live in config/routes.rs:
pub fn draw(r: &mut Routes) {
r.resources::<PostsController>("posts");
r.get("/up", nails::health::show).as_("nails_health_check");
}
Views
Views are Jinja templates in app/views. Rails helpers keep their names and
use Jinja call syntax. This is the scaffold's index.html.jinja:
<p style="color: green">{{ notice }}</p>
{{ content_for("title", "Posts") }}
<h1>Posts</h1>
<div id="posts">
{% for post in posts %}
{% include "posts/_post.html.jinja" %}
<p>
{{ link_to("Show this post", post_path(post)) }}
</p>
{% endfor %}
</div>
{{ link_to("New post", new_post_path()) }}
Tests
nails test runs test/. Each test gets its own database, loaded with the
YAML fixtures in test/fixtures and rolled back at the end:
#[test]
fn should_create_post() {
let (mut t, post) = setup();
assert_difference(|| Post::count().unwrap(), 1, || {
t.post(&t.path("posts"), &[
("post[title]", post.title.clone()),
("post[body]", post.body.clone()),
("post[published]", post.published.to_string()),
]);
});
t.assert_redirected_to(&t.path_for("post", &Post::last().unwrap().unwrap()));
}
System tests drive headless Chrome. nails g system_test posts creates
test/system/posts_test.rs, and nails test:system runs it. A failing
system test saves a screenshot to tmp/screenshots/.
#[test]
fn creating_a_post() {
let t = browser();
t.visit(&t.path("posts"));
t.click_on("New post");
t.fill_in("Title", "Hello");
t.click_on("Create Post");
t.assert_text("Post was successfully created.");
}
Databases
Apps use SQLite by default. For Postgres, pass -d postgresql, as in Rails:
nails new blog -d postgresql
See docs/databases.md for database.yml,
DATABASE_URL and how tests run on Postgres.
Rails → Nails
A few common mappings. The full list covers associations, jobs, mail, testing and the CLI.
| Rails | Nails |
|---|---|
class Post < ApplicationRecord |
#[nails::model] struct Post |
has_many :comments, dependent: :destroy |
#[has_many(Comment, dependent = destroy)] |
Post.where(title: "x").order(...) |
Post::where_eq("title", "x").order("...").load() |
resources :posts |
r.resources::<PostsController>("posts") |
params.expect(post: [:title]) |
c.params().expect("post", &["title"]) |
app/views/posts/index.html.erb |
app/views/posts/index.html.jinja |
CleanupJob.perform_later(post) |
CleanupJob { post: RecordRef::of(&post)? }.perform_later()? |
bin/rails test |
nails test |
bin/rails console |
nails console |
How Nails compares
Loco is also a Rails-inspired Rust framework. The differences:
- Loco app code is async. Nails models and controllers are synchronous, like Rails.
- Loco uses SeaORM. Nails has its own Active Record layer.
- Loco has its own layout and names. Nails copies Rails as closely as Rust allows.
- Loco is older, with releases and a community. Nails is new.
Rust on Nails has a similar name but is a guide and starter template, not a framework. The two projects aren't related.
Contributing
Rails features Nails doesn't have yet (Active Storage, Action Cable, MySQL, Kamal deploys and more) are tracked as Rails parity issues. Pick one up, or open an issue for anything else you miss.
See CONTRIBUTING.md for setup, running the tests and how the code is laid out.
Contributors
Thanks to everyone who has contributed to Nails. The emoji key explains each contribution type.
Wes Grimes 💻 📖 🚧 |
Matt Briggs 💻 |
Affiliation
Nails is an independent project inspired by Ruby on Rails. It is not affiliated with or endorsed by the Ruby on Rails project.
License
Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in Nails by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.
Explore related projects
Loading…
