Zac Stewart - Big Nerd Ranch Tue, 19 Oct 2021 17:46:35 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 Why We Teach Rack in our Ruby on the Server Bootcamp https://bignerdranch.com/blog/why-we-teach-rack-in-our-ruby-on-the-server-bootcamp/ https://bignerdranch.com/blog/why-we-teach-rack-in-our-ruby-on-the-server-bootcamp/#respond Thu, 23 Oct 2014 10:10:22 +0000 https://nerdranchighq.wpengine.com/blog/why-we-teach-rack-in-our-ruby-on-the-server-bootcamp/

When I teach our web services class Ruby on the Server, a question I
occasionally get from students is why we spend half of the first day learning about Rack.
After all, Rails is the heavyweight of the Ruby ecosystem, and what most people
come to learn about.

The post Why We Teach Rack in our Ruby on the Server Bootcamp appeared first on Big Nerd Ranch.

]]>

When I teach our web services class Ruby on the Server, a question I
occasionally get from students is why we spend half of the first day learning about Rack.
After all, Rails is the heavyweight of the Ruby ecosystem, and what most people
come to learn about.

One of the core themes of the class is to demystify Rails, which has a lot of
features that people often describe as “magic.” When people say that, what
they usually mean is an interface with a level of abstraction that frees you
from needing to know what’s going on under the hood. It gives you that “it
just works” sensation. Being free to build your application without worrying
about the underlying implementation is wonderful, but sadly, many developers
never peel back the layers and attempt to understand how it works.

At Big Nerd Ranch, our approach is to teach the bare bones first. We apply this tactic over and
over throughout the week, from rendering an ERB template by hand to defining
resourceful HTTP routes and mapping them individually to controller actions. We
make you do it the hard way before we teach you the magical incantations. Think
of it as watching the Wizard of Oz backwards. Instead of jumping directly into
Rails and seeing your web service magically spring to life, we start with Rack.

This is not just some pedagogical theory, though. It has practical value.
Sufficiently complex Ruby web services are often split into multiple
sub-services. Rack is a specification designed to build modular web services
that can be composed. Whether it’s a simple web interface to view your
background job queue or a full blown service-oriented architecture, you’ll
encounter such services in the wild. They will almost certainly be Rack apps.
“Not Rails apps?” you ask. The wonderful thing is that Rails apps are Rack
apps, and so are Sinatra, Padrino and Lotus apps. It would be easier to note
exceptions than to compile a list. These days, it’s safe to assume that if it’s
serving up HTTP responses, and it’s written in Ruby, then it’s a Rack app.

Understanding Rack is essential to deeply understanding how a complex web service
written in Ruby works.
We’re not training you to be able to complete the
cliché blog tutorial. We want you to go home armed with the knowledge needed to
contribute to the kind of projects we work on.

Change of Rack Maintainer

With such wide usage, it came as a bit of a shock when the Rack core team
announced that Rack is considered complete. Aaron
Patterson will step up to maintain point releases going forward, but the team
does not expect to release version 2.0 of Rack. I recommend reading the
announcement yourself for a fuller picture, but the gist of it is that Rack is
showing its age.

There’s a multitude of new protocols on the horizon, like WebSockets, HTTP2,
and Server-Sent Events, to name a few. Many implementations of the Ruby
language now have usable multi-threading. The world simply isn’t the same place
it was when the Rack specification was introduced.

The Future of Ruby Web Services

That said, for now, and a long time to come, you will still use Rack. It remains an
important part of the Ruby web stack and won’t be going anywhere for a while.
Even so, we need to be thinking about the future. Where will Ruby fit into
the event-driven, “real-time” future of the web? Does it have a place?

Whatever comes next needs to be designed for a world where resources can exist
not only as documents, but as streams. Our Chief Learning Officer Aaron Hillegass
talked about this at AltConf earlier this year.

I think that if there’s room for Ruby in the traditional web service space,
where Java is king, then there’s room in this new space. Go and Elixir may be
extremely well suited for the job, and I expect them to capture a significant
portion of the market. However, Ruby has a winning characteristic: its flexibility.
The ease with which you can kick off a project, iterate on the design and get
a working product out the door is unparallelled.

I share Aaron’s excitement for the future of WebSockets, Server-Sent Events
and the like. However, I think there’s reason to keep some stock in stateless
protocols like HTTP: the inherent unpredictability of mobile network
connectivity. WebSockets are awesome for broadcasting events to multiple
devices in near real-time, partly because they hold open a persistent
connection. However, when you lack the requisite, stable connection, that
characteristic is less exciting. As much as we all want
ubiquitous, reliable broadband, unreliable connectivity is, sadly, the state
of mobile internet for the foreseeable future. When you get off a plane in an unfamiliar city,
being able to send a request for a car from your favorite rideshare app under
sketchy network conditions will be of higher value than seeing real-time car
locations on a reliable connection.

Event sourcing application state over a streaming protocol will remain
unpractical for quite some time. Imagine downloading every change that ever
occurred to a Wikipedia page over a WebSocket just to get the end result.
Consequently, I believe we’ll see a proliferation of hybridized web services.
In between traditional request-response services and event sockets for
everything, there’s a whole world of practical applications where resources can
exist as documents or streams, like chat transcripts and real-time chat, or Wikipedia
pages and real-time, collaborative editing.

The building blocks for event-driven web services have been making their way
into the Ruby ecosystem for a few years now. Couple that with battle-tested,
traditional web service frameworks like Rails, and Ruby is in an excellent
position to continue being the language of choice for web developers.

Rails introduced ActionController::Live with version 4.0, although it feels
bolted on at best. Rails doesn’t have a first-class way of representing
resources as streams. Others have been researching ways to create hybrid
resourceful/eventful web services:

  • Matt Thompson’s Rocket exposes
    resources in a traditional RESTful manner, and as a stream using a non-standard
    HTTP method (SUBSCRIBE) and Server-Sent Events.
  • Faye is pub/sub
    messaging system that can be mounted into a Rack application.
  • Aaron Patterson
    has done some research on a successor to Rack 1.0, but it’s still
    very experimental. It may reduce the scope of Rack by dropping middleware, but
    will hopefully be compatible with new streaming protocols.

What It Means for Ruby on the Server

For the foreseeable future, we’re still teaching Rack. It’s a stalwart of Ruby
web services, and isn’t going away any time soon. We believe that understanding
Rack is paramount for being able to tackle complex Ruby applications today, and
for a long time to come.

That said, things are changing. These are exciting times, and we’re making the most of them. Always learning,
we’re putting an increasing focus on evented protocols across all our
engineering divisions. We’re conducting internal experiments and doing awesome
work for clients.

What we learn, you’ll learn. Coming early next year, the Ruby on
the Server bootcamp
will teach you to build evented web services as a first-class
topic. We’re excited about this unchartered territory, and seeing what will be
built in it.

The post Why We Teach Rack in our Ruby on the Server Bootcamp appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/why-we-teach-rack-in-our-ruby-on-the-server-bootcamp/feed/ 0
Space Apps Atlanta https://bignerdranch.com/blog/space-apps-atlanta/ https://bignerdranch.com/blog/space-apps-atlanta/#respond Tue, 19 Mar 2013 20:23:16 +0000 https://nerdranchighq.wpengine.com/blog/space-apps-atlanta/

Space Apps Challlenge

The post Space Apps Atlanta appeared first on Big Nerd Ranch.

]]>

Space Apps Challlenge

We’re proud to announce that we’re hosting the Atlanta chapter of NASA’s International Space Apps Challenge. Space Apps is a chance for developers, designers, engineers, artists and tinkerers to team up and work on some of the exciting challenges published by NASA.

For 48 hours on April 20-21, participants will work in teams on challenges involving web services, data visualization, open hardware and more. The available challenges include projects like designing next-gen payloads for ArduSats, creating a 3D-printable model of a component from an ESA mission, visualizing Voyager 1’s journey and improving access to NASA datasets.

A key tenet of Space Apps 2013 is collaboration. Accordingly, we will facilitate and encourage joint efforts with remote participants and other locations around the world. If you can’t be at the event in person, we still invite you to work on a project with us as a virtual participant!

To kick off the event, we’ll be having a reception on Friday, April 19. Space is limited, so register now to ensure you have a spot. If Atlanta is out of your range, find your nearest location.

Check out the rest of the challenges. Which would you like to work on the most? Let us know via @spaceapps_atl and follow our progress on GitHub.

The post Space Apps Atlanta appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/space-apps-atlanta/feed/ 0
Breaking table–model–controller symmetry https://bignerdranch.com/blog/breaking-table-model-controller-symmetry/ https://bignerdranch.com/blog/breaking-table-model-controller-symmetry/#respond Sun, 16 Dec 2012 21:28:06 +0000 https://nerdranchighq.wpengine.com/blog/breaking-table-model-controller-symmetry/

A while ago, I hit a lull in my skill advancement as a Rails developer. I had long since learned to think of my resources as resources. I did my best to limit my controller actions the basic CRUD methods. I considered the “fat model, skinny controller” mantra to be sacrosanct. But I was still often finding myself going way out of my way to implement otherwise mundane features, for example sending mail after saving an object or adding a routine accept/reject to something.

The post Breaking table–model–controller symmetry appeared first on Big Nerd Ranch.

]]>

A while ago, I hit a lull in my skill advancement as a Rails developer. I had long since learned to think of my resources as resources. I did my best to limit my controller actions the basic CRUD methods. I considered the “fat model, skinny controller” mantra to be sacrosanct. But I was still often finding myself going way out of my way to implement otherwise mundane features, for example sending mail after saving an object or adding a routine accept/reject to something.

I realized that one simple assumption was holding me back: that there should be a one-to-one ratio of database tables, models and controllers. Discovering the power of additional controllers, decorators, service objects, form objects and other supplements to the standard models, view and controllers of Rails has been a boon to my productivity and I’d like to share a few patterns I’ve found useful.

Extracting auxiliary objects

Let’s say you want to add a notification system to your application. You want users to have a notification area listing all their unread notifications and you want them to receive an email every time they get a new one. At first, it might be easy enough just to create the notification and then send mail from the controller, but as the events which cause a notification to be created grow, you find yourself writing that same few lines again and again. It’s time to abstract that away.

One way to do this would be to use an after_create hook on your Notification model to send mail. This would jibe with the “fat model, skinny controller” principal, it even DRYs up your code, but that doesn’t mean it’s right. Using ActiveRecord callbacks to manipulate external objects can obfuscate intent and make testing difficult. If you abuse them, you can turn your application into confusing callback spaghetti.

A clearer way to abstract this feature is to create a supporting object, i.e. a Notifier:

Here’s how you could use it from a controller:

An excellent post on this topic that I’ve drawn on heavily is 7 Patterns to Refactor Fat ActiveRecord Models by Bryan Helmkamp.

As a side note, if you’re curious as to where to organize these bits, you can’t really hurt yourself by creating another directory under app/. I often have directories like decorators and services there.

Exposing additional resources

Sometimes you want to perform a simple operation on a resource–for example, administrator approval of a blog comment. In terms of your model, all you want to do is flip an “approved” boolean on the comment. It can be temping to just add another action to your controller, route a POST request to it and call it a day. The authors of RESTful Web Services refer to this as overloaded POST. You’re essentially trying to augment HTTP with a new method. In some cases, this may be appropriate but more often it’s indicative of poor resource design.

Another solution that a more REST-minded developer might come to is to utilize the HTTP PUT (or more correctly, PATCH) method and the update controller action. Rails makes this pretty easy by letting you include form parameters and specify the method of a hyperlink using link_to. This too is less than ideal, though. For one, you’re going to end up with a lot of conditional logic within the update method. If you’re using something like the state_machine gem you can end up with some funky-looking code like this:

While seeming more “RESTful” at first, this may actually be worse than overloaded POST. You could call this overloaded PUT and while POST is allowed to be kind of a wildcard, PUT is expected to be idempotent: whether you do it once or a million times, the outcome should be the same. Approving a comment a million times is bordering on nonsensical.

Willem van Bergen studied this pain point in his post RESTful thinking considered harmful and concluded that the best solution for these kind of transactional update operations is overloaded POST. He made the excellent observations that not all updates are equal, REST does not equal CRUD, and updating a resource does not always correspond to the UPDATE operation in a database–all concepts that Rails literature tends to conflate. However, I feel it’s too early to throw in the towel and declare REST inadequate for your problem space.

A more appropriate solution is just to expose another resource, another noun. You don’t have to approve a comment, you can create an approval for it. An approval doesn’t have to map directly to a database table of approvals to be a valid resource, either.

You can add a couple subordinate resources, “acceptance” and “rejection,” to your comments resources in routes.rb:

And add two controllers like this one:

This effectively eliminates all the conditional logic previously handled by update, or a least relegates it to a matter of routing.

Objects for complex forms

Occasionally, you need to create and persist more than one ActiveRecord model at once. For example creating a User and a new Blog for them upon signing up. The built-in solution for this is accepts_nested_attributes_for. This solution works, but how it does has always seemed incredibly opaque to me. Furthermore, it isn’t very flexible and becomes more confusing per each level of nested resources.

Another tricky situation is when you want to create ActiveRecords in a way that diverges from the typical CRUD actions. For example if you have a blog application similar to Tumblr that lets you reblog a blog post. A reblog is essentially a duplicate of the original, potentially with some modification or addition to its attributes, for example adding a citation of original author and keeping a pointer back to the original. You could use the patterns explored in the previous section to expose a reblog resource for each blog, but in this case you’d probably end up with a pretty complicated ReblogsController.

A simpler solution that can address both of these situations is to roll your own form object. Basically, all you need is something that quacks like an ActiveRecord model and can turn the parameters you provide it into the models that you need. To achieve that, you just need to mix in a few parts of ActiveModel. I also like to use a gem called Virtus to provide ActiveRecord-like attributes so that you can easily instantiate an object using the params attribute.

Now you can create a simple ReblogsController to use it:

As you can see, there are occasionally situations that can be addressed by leaning on some classical object-oriented patterns and RESTful practices beyond Rails’ core design. Remember: your database schema is not your application. That said, you don’t want to use these techniques too heavily, making your app incomprehensible or too non-standard.

Since applying these techniques, I’ve noticed a marked decrease in those situations where I could build _something _that got the job done but didn’t feel right. I spend much less time deliberating over minutiae and more time thinking about the larger goal.

The post Breaking table–model–controller symmetry appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/breaking-table-model-controller-symmetry/feed/ 0
Lazy User Registration for Rails Apps https://bignerdranch.com/blog/lazy-user-registration-for-rails-apps/ https://bignerdranch.com/blog/lazy-user-registration-for-rails-apps/#respond Mon, 08 Oct 2012 12:00:00 +0000 https://nerdranchighq.wpengine.com/blog/lazy-user-registration-for-rails-apps/

enter here

The post Lazy User Registration for Rails Apps appeared first on Big Nerd Ranch.

]]>

enter here

Requiring a would-be user to go through a sign-up process can often be too much to ask. Instead of jumping through your hoops, many people will just hit the ‘back’ button and continue browsing Reddit without ever discovering how cool your app is. In fact, I do it all the time.

Instead, why not treat your visitor as a valued customer with all the rights and privileges of a full-blown user from the get-go? With soft sign-ups, you can do just that.

Delayed registration, soft sign-up, lazy registration–whatever you like to call it, it has one simple purpose: to remove a barrier between your customer and your product.

But I want my users to register!

Even if you want your content to be as accessible as possible, there are still two basic reasons why you’d require registration:

  1. to prevent unauthorized access to private content
  2. to have something to silo user-created content with

The first is a users’s concern; let’s let them decide when to lock down their account with a password.

The second is our focus. Unless you’re Wikipedia, you can’t just let visitors start creating and editing content without any way to sort out who owns what. However, this is a technical constraint that can easily be overcome with soft sign-ups.

The omnipresent anonymous user

The most basic requirement for a soft sign-up is that there must be a current_user at all times. You also want this user to be persistent (i.e., they’re not someone new with every page load). The example below uses Devise, but could easily be adapted to the auth system of your choice.

There are three methods here:

  • anonymous_user_token returns a unique identifier attached to the visitor’s session. This will persist for the duration of the user’s current session.
  • current_user overrides the default Devise method. It first does what it normally does–returns the currently logged in user–but if one doesn’t exist, it falls back to finding or creating a new AnonymousUser with the unique anonymous_user_token.
  • authenticate_user! behaves like it normally does with Devise, except it’s more lenient and allows an anonymous user.

You may choose to create another before filter method instead of overriding authenticate_user! if you want to restrict an anonymous user in some way other than a registered user.

Another thing you may note is the AnonymousUser class, which inherits from User. This is not necessary, but just one way to differentiate anonymous and registered users. You may prefer to use a role-based system instead.

That’s the meat of it. With those few lines of code, visitors should be able to start using your app like a normal, registered user.

Registering (and keeping all your work)

So now that your users have been able to start using your product right away, they’ve probably found out that it’s really awesome and they want to become a member.

Will they get to keep all the stuff they’ve been working on? Of course!

From a technical perspective, this is more akin to updating their profile in order to change their email and password. But for an end user, it’s magic: They get to transition into registered user-dom whenever they’re ready, while keeping all the stuff there were already doing.

First, we need to tell Devise that we’re going to be overriding the registration controller via routes.rb.

Then we need to override how Devise handles registrations with the RegistrationsController.

Like I said, it’s basically just updating the current_user and re-signing them in. I have a little method on AnonymousUser called register to help do that:

You’ll need to change a little view logic as well. For example, you’ll want to check something like current_user.anonymous? instead of present? to conditionally show your “Sign in” and “Sign up” links.

That’s pretty much all there is to it. With soft sign-ups, visitors can begin using your product right away. If they use your app and want to register, they can transition easily into a full user while retaining all their content.

Image credit: potential past

The post Lazy User Registration for Rails Apps appeared first on Big Nerd Ranch.

]]>
https://bignerdranch.com/blog/lazy-user-registration-for-rails-apps/feed/ 0