Rails Metal Example #3: Simple API’s

A few weeks ago, I wrote 9 Ways to Use Rails Metal. The third way to use Rails Metal was implementing a simple API.

Before I provide the code and an explanation, I’d like to cover a few things. First, this API only requires an API key. If you want an authentication token or some other identifier, look at Rails Metal Example #1: Authentication for some ideas of how to manage authentication for your API. Second, I didn’t filter any contents on the User model, so the password is passed back by the API. A simple delete call for the keys you want to omit from the hash returned by the find_by_sql call should clear up any data you don’t want to pass back.

Here’s the code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
# Allow the metal piece to run in isolation
require(File.dirname(__FILE__) + "/../../config/environment") unless defined?(Rails)
 
class ApiHandler
  def self.call(env)
    req = Rack::Request.new(env)
    @params = req.params
    if (env["PATH_INFO"] =~ (/^\/api\/(xml|json)\/user\//)) && ApiKey.find_by_key(@params["key"]) && env["REQUEST_METHOD"] == "POST"
      format = env["PATH_INFO"].split("/")[2]
      return [200, {"Content-Type" => "application/xml"}, [User.find_by_sql(["SELECT * FROM users WHERE id = ?", @params["id"]]).to_xml]] if format == "xml"
      [200, {"Content-Type" => "application/json"}, [User.find_by_sql(["SELECT * FROM users WHERE id = ?", @params["id"]]).to_json]] if format == "json"
    else
      [404, {"Content-Type" => "text/html"}, ["Not Found"]]
    end
  end
end

The code here is pretty simple. You check the path to make sure it matches the api path for XML or JSON, then find the record, convert it, and send it off to the user.

A few things to note are that the Rails methods to_json and to_xml are available in Rails Metal. I also had to explicitly return on the xml format because it isn’t the last execution and therefore isn’t returned.

  • Facebook
  • LiveJournal
  • Squidoo
  • Delicious
  • Digg
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati Favorites
  • Slashdot
  • Reddit
  • Twitter
  • Share/Save/Bookmark

Print Debug Information to Its Own Log

Setting up a Debug Log

Have you ever been debugging your Rails application and watching the development log fly by wishing that you could put output just the information you need to its own log? There’s actually a quick and easy way to do it.

First, you create your logger.

1
@debug_log = Logger.new(File.open(File.dirname(__FILE__) + "/../../log/debug.log", "w"))

Then you log data to it.

2
@debug_log.debug @object

It’s simple and it makes the data extremely easy to find. Just take the statements out when you’re done debugging.

  • Facebook
  • LiveJournal
  • Squidoo
  • Delicious
  • Digg
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati Favorites
  • Slashdot
  • Reddit
  • Twitter
  • Share/Save/Bookmark

31 Days to Build a Better Blog: Week 3

31 Days to Build a Better Blog

31 Days to Build a Better Blog

After the third week of doing the 31 Days to Build a better blog, I’m seeing the traffic and participation on my blog increasing by leaps and bounds. This last week, the traffic increase was due primarily to being featured in the Rails Envy Podcast. The idea to email Gregg Pollack about my post 9 Ways to Use Rails Metal came from step 3 in the 31 days.

You can see from the google analytics I’ve included in this post that Wednesday and Thursday I saw significant traffic. About half of that was from Rails Envy.

Traffic from Week 3 - 31 Days to Build a Better Blog

Traffic from Week 3 - 31 Days to Build a Better Blog

Overall, I’m extremely pleased that this system has helped so many people find what I’m offering. I’m also excited that it appears to help some people with their Ruby on Rails applications. It’s encouraging me to think about other ways I can contribute to the community. You’ll probably see posts in the upcoming weeks regarding some of the things I’ll be doing to chip in and help a few more people with Ruby on Rails.

Follow this link if you’re interested in getting 31 Days to Build a Better Blog.

  • Facebook
  • LiveJournal
  • Squidoo
  • Delicious
  • Digg
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati Favorites
  • Slashdot
  • Reddit
  • Twitter
  • Share/Save/Bookmark

Rails Metal Example #4: Redirecting Affiliate Links

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:

1
2
3
4
5
6
7
8
9
10
11
12
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.

  • Facebook
  • LiveJournal
  • Squidoo
  • Delicious
  • Digg
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati Favorites
  • Slashdot
  • Reddit
  • Twitter
  • Share/Save/Bookmark

31 Days to Build a Better Blog: Week 2

31 Days to Build a Better Blog

31 Days to Build a Better Blog

This is the second week I’ve been doing the 31 days to build a better blog. I’ve completed steps 3 through 7 this week and have seen an explosion of traffic on my blog. (See week one.)

Comparing the week (Saturday to Friday) of June 7th to the week of June 14th I’ve seen my visits jump from 34 to 198. That’s almost a 6 times increase in traffic. Here’s the graph from google analytics comparing the two weeks.

Traffic from June 14-20 vs June 7-13

Traffic from June 14-20 vs June 7-13

I thought I’d see a slight uptick in traffic from following these steps, but I had over 6 times the page views and just under 6 times the visits. My new visitors was down slightly, but what that really means is that I’m getting more and more return readers to my blog.

The information in this booklet is pure gold! I’m going to get my Dad blogging for his dental practice and we’re going to apply these same principles to get his traffic and readship up just as quickly. To say I’m pleased would be a gross understatement. I’m really excited.

Look out for my report next Monday.

  • Facebook
  • LiveJournal
  • Squidoo
  • Delicious
  • Digg
  • Google Bookmarks
  • LinkedIn
  • StumbleUpon
  • Technorati Favorites
  • Slashdot
  • Reddit
  • Twitter
  • Share/Save/Bookmark