views:

132

answers:

3

I'm trying to work with the data in my Rails application from within a separate Ruby script.

I read this forum post in which some people suggest that the best way to work with your data is to encapsulate the database within one application, and then have this application provide an API for working with that data. Because it's apparently bad to integrate your database into several different applications.

Well, now I want to work with some data from my Rails app from another script, but on the same system. How can I achieve this?

I might want to work with the data from my Rails app remotely in the future, but also from a script. I'm assuming this might require JSON or SOAP, but I would like to know before I go researching it.

A: 

Accessing the data is simple too, just make a request to your application using something like HTTParty. Look at the examples, they're pretty good.

Ryan Bigg
+5  A: 

Have you take a look at ActiveResource? It's specifically designed to expose data from a Rails model to another Rails app over HTTP.

Yehuda Katz
Thanks. I've looked up Active Resource and started tinkering with it, this is exactly what I'm looking for. Combined with basic HTTP authentication and SSL, this fits my needs beautifully, thank you.
Blaine LaFreniere
+1  A: 

Since Ruby on Rails follows REST, your application is, by default, it's own API. For example, say you have the following controller:

class UsersController < ApplicationController

  def show
    @user = User.find(params[:id])
    respond_to do |format|
      format.html
      format.xml  { render :xml => @user}
      format.js
    end
  end

  def index
    @users = User.all
    respond_to do |format|
      format.html
      format.xml  { render :xml => @users}
      format.js
    end
  end
end

Now, when hitting that controller via the web browser, it will render your views as you would expect. For example:

GET /users/1   =>  /app/views/users/show.html.erb
GET /users     =>  /app/views/users/index.html.erb

However, if you change your requests to be something like:

GET /users/1.xml
GET /users.xml

You'll be returned XML data instead of your HTML views. You can now access this data from any other application by using some sort of REST Client, or simply by calling cURL from any command line.

You can append any extension to the end of your URL, and it will find the appropriate respond_to section.

Mike Trpcic
I discovered this after reading the answer from Yehuda Katz. Your answer, combined with Active Resource, is exactly what I was looking for. Thank you for the additional info.
Blaine LaFreniere