Posts tagged as:

middleware

Rack is the basis for most major web frameworks in Ruby (like Ruby on Rails.) This video gives a basic overview on how it is used and what features make it a powerful component for Ruby Web Frameworks

Download 36 MB
Download (iPod & iPhone) 25 MB

{ 10 comments }

A week and a half ago, I posted 9 Ways to Use Rails Metal. The fourth way I listed was “Redirecting Affiliate Links.” The basic idea is that you can set up http://mydomain.com/hosting to go to the link you were given by the hosting company you have an affiliate account with.

The first thing I did was set up a model to manage affiliate redirects.

script/generate model affiliate_redirect path:string location:string

Then I ran my migrations, to set up the database.

rake db:migrate

Then I set up a Rails Metal instance called affiliate_redirects.

script/generate metal affiliate_redirects

From there, programming Rails Metal was pretty simple. You just have to find an AffiliateRedirect with the path visited and redirect to the AffiliateRedirect’s location. Here’s the code:

require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class AffiliateRedirects
  def self.call(env)
    redirect = AffiliateRedirect.connection.select_all("SELECT * FROM affiliate_redirects WHERE path = '#{env["PATH_INFO"]}'").first
    if redirect && (location = redirect["location"])
      [302, {"Content-Type" => "text/html", "Location" => location}, ["You are being redirected."]]
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

This is the quick solution to the Rails action with nothing but a redirect_to.

{ 0 comments }

Last week, I wrote a post listing 9 ways to use rails metal. This is an explanation of the first way to use Rails Metal: Check Authentication.

We’re setting up this Rails Metal to handle two scenarios: requiring authentication, and logging the user in. First, it verifies that requests to any path beginning with /admin have a user logged in by checking that a valid user id is stored in the session. Second, accepts an HTTP POST to /authenticate with a username, password, and target path for redirect upon

Before we get too deep into things, let me share the code. You can check out a working version of the application on GitHub.

Here’s the Metal.

require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)

class Authentication
  def self.call(env)
    session = env["rack.session"]
    request = Rack::Request.new(env)
    params = req.params
    if env["PATH_INFO"] =~ /^/admin.*/ && (session["user_id"].nil? || (session["user_id"] && User.connection.select_all("SELECT * FROM users WHERE id = #{session["user_id"]}").empty?))
      [302, {"Content-Type" => "text/html", "Location" => "/login?target_path=#{env["REQUEST_URI"]}"}, ["You must be logged in to view this page. You are being redirected."]]
    elsif env["REQUEST_METHOD"] == "POST" && env["PATH_INFO"] =~ /^/authenticate/
      users = User.connection.select_all("SELECT * FROM users WHERE username='#{params["user"]["username"]}' AND password='#{params["user"]["password"]}'")
      unless users.empty?
        session["user_id"] = users.first["id"]
        [302, {"Content-Type" => "text/html", "Location" => "#{params["target_path"] || "/"}"}, ["You have been logged in. You are being redirected."]]
      else
        [302, {"Content-Type" => "text/html", "Location" => "/login"}, ["Authentication failed. You are being redirected."]]
      end
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

Bases for Understanding the Code

There are a few methods and structures here that are important to note in how this all works.

First, the self.call(env) is the entry point for the Rails Metal application. env refers to the Rack environment.

Next, Rack::Request is a class that provides a convenient interface to the Rack environment. In this case, we’re using it to extract the GET and POST parameters from the request. You can see the full Rack::Request API here.

env[‘rack.session’] returns the session as a hash. In this case, keys are accessed as strings, not symbols. So, in our case, session[:user_id] won’t work, but session[“user_id”] will work.

Finally, we do direct SQL calls through the ActiveRecord object rather than using the find method because it’s faster and we only need a few fields like the id of the user that’s found.

Overview of the Code

Checking Authentication

Our authentication code creates a session variable called user_id and places the current user’s id into it. So, to make sure someone is logged in, we need to make sure that a valid user id is in the session.

To do this we check if the path begins with /admin. env[“PATH_INFO”] contains the path without any GET parameters. So, we do a regular expression match and them move on to checking if there’s a valid user id in the session.

There are two scenarios that we need to check. There is no user id stored in the session and the user id stored is not the id of a valid user.

If both conditions are met, we redirect the user to /login and pass along the path the user was trying to access as a GET parameter called “target_path.”

Logging the user in

If a valid username and password are passed to the path /authenticate, we need to store the user’s id in the session and redirect them to where they were trying to go. To check the username and password, we query the database. If no matches are found in the database, then we send them to the login page.

Overall the code is pretty simple. Feel free to use it in any of your applications. I’ll post the benchmarks when I get a chance, but several people were looking for this content, so I’m putting it out now.

{ 7 comments }

Have you ever wished you could mix Rack or Sinatra into your Ruby on Rails application just to get its raw throughput on certain parts of your application?

Let’s face it, sometimes, the Rails framework is overkill when we’re returning a simple string or an object in JSON as our response. Your answer for these instances is here. Rails Metal.

Performance

Some people have reported huge speed increases in Rails Metal over the Rails MVC framework. This article claimed a 25x increase over Rails. Pratik Naik from the Rails Core team benchmarked a more believable increase of 4x. Whatever the case, the performance advantage is worth noting.
[click to continue…]

{ 5 comments }

I’ve been playing with Rails Metal for quite some time now. Under certain circumstances, one Metal would catch something I intended for another metal deeper in the middleware stack. Reordering became the order of the day. The only problem was that the Rails Guide was in the works and I didn’t want to hack my metal files to put them in alphabetical order to match the order I wanted them in.

So, without further ado, here is how you reorder your Rails Metal middleware stack:

Open you environment.rb file:

vi config/environment.rb

Then add this line inside the initialization block:

config.metals = ["FirstMetal", "ThirdMetal", "SecondMetal", "FinalMetal"]

The strings in the array are the names of the metal files in camel case.

{ 3 comments }

One of the greatest features in Rails 2.3 is the Rails Metal piece. It’s part of the goodness that came out of the Rails/Merb merge.

Metal provides a layer of functionality that is executed before or in the place of your rails application. The common term for this type of software is middleware. There is a terrific presentation that was given at Mountain West RubyConf 2009. You can actually view the video of it here.

Here’s a simple example of how to use metal to require authentication before accessing pages on the site.
[click to continue…]

{ 1 comment }