December 12, 2006 @ 10:32 AM
Taking ARes Out For a Test Drive
Although ActiveResource was announced last June during David’s World of Resources talk at RailsConf, it has yet to see an official release. It currently lives in the rails svn trunk with the rest of Rails, but was left out in the 1.2 Pre Release. A few rails developers (myself included) have been plugging away at it little by little as we’ve been implementing little REST services. (The only public example I know of is Blinksale, which uses what looks like a compatible interface. However, they provide their own REST::Client library as a sample ruby client lib, instead of ARes). From what I gather, ARes is only being used in limited, private services, but I think it’s time to get it out in the open. My goal with this (and possibly more, making this a series of articles) is to get the word out on where we’re at with ActiveResource, and hopefully get some folks interested in helping out.
For those that don’t know, ActiveResource is a client-side XML consumer for APIs created by the latest Rails restful additions. Consider it your reward for figuring out how to wield map.resources appropriately and restructuring parts of your app around it. That’s right, follow these rules, and you’ll get most of a server API and a client library for free.
Installation
Since ActiveResource isn’t released, how do we start playing with it? Probably the easiest way (until a gem is released) is by checking out the whole rails trunk and requiring both ActiveSupport and ActiveResource:
$ svn co http://dev.rubyonrails.org/svn/rails/trunk
$ irb
> require 'activesupport/lib/active_support'
> require 'activeresource/lib/active_resource'
Note: if you don’t already have a checkout of the rails trunk somewhere, all you actually need are ActiveSupport and ActiveResource.
Building a Client API Library for Beast
If you’re still following along with us in irb, you can go ahead and create the ActiveResource classes and start using it. First, we’ll create a base class that will set up the Beast site URL, as well as the optional user/password if you want to make changes.
1 2 3 4 5 6 |
class BeastResource < ActiveResource::Base # any recent trunk version of Beast will work here self.site = 'http://beast.caboo.se' # site.user = 'rick' # site.password = 'secret sauce' end |
Now that we have that, we can create classes for the four main resources we’ll be dealing with: users, forums, topics, and posts. Users and forums will be straight forward. Topics and Posts, however, are nested resources. They will need a site value that matches the path prefix set by map.resources in Beast.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
class User < BeastResource end class Forum < BeastResource end class Topic < BeastResource self.site += '/forums/:forum_id' end class Post < BeastResource self.site += '/forums/:forum_id/topics/:topic_id' end |
That’s all there is to it. Now, let’s play around.
1 2 3 4 5 6 |
f = Forum.find 1 # notice that since Topic has a prefix, we must pass the forum_id. # This is so it can make the request to /forums/1/topics/1.xml t = Topic.find 1, :forum_id => f.id p = Post.find 1, :forum_id => f.id, :topic_id => t.id u = User.find p.user_id |
If that all worked, you should be able to experiment with Beast. If you create any posts, please do so in the Testing forum.
1 2 3 4 5 6 7 8 |
forums = Forum.find :all testing = forums.detect { |f| f.name == 'Testing' } # initialize takes two parameters in ActiveResource. One for the model parameters, and one for the prefix parameters. topic = Topic.new({ :title => 'Testing out ARes', :body => 'Testing 1, 2, 3!'}, { :forum_id => testing.id }) |
You may notice a few odd things here. First, #initialize takes a second hash param for the prefix options. This is so it can POST to /forums/5/topics.xml. Also, if you look at the schema for a topic, there is no body attribute. Beast cheats a little bit here and creates both a topic and the first post from one request.
ActiveResource doesn’t know the schema and will basically send whatever you give it. If you’re a little mischievous, you may try making requests to change the posts-count, updated-at, and other “unchangeable” fields. Luckily, Beast protects its attributes with attr_accessible, so this won’t be an issue.
That’s about it for part one of this series. Hopefully you have a little more understanding of where we’re at with ActiveResource, and have had a chance to knock it around a bit. In future articles, I’ll talk about how to customize your Resources for custom applications, how to correctly build API support that ActiveResource can understand, and go into what work remains for ActiveResource. If you want to see how it works from the server side, check out Beast.

by JontheWayne on 13 Jan 15:18
Rick, This is such a brilliant post! When I first saw David’s presentation on Active Resource back in June, my mouth was agape in amazement at the coolness of a server api for free. Rails is seriously just getting more and more irresistable. Thanks for working so hard on this release!
by Pat Maddox on 13 Jan 15:20
ARes kicks ass, I don’t know why it hasn’t taken hold more. Perhaps it’s due to a lack of exposure? I’m not sure. Anyway I use it in a billing system I wrote…credit card info is stored encrypted and split among a couple servers. When I need to process a card, one server sends a POST to /payments on the other one, sending along its card info and then an id key. The other server puts them together, decrypts, charges the cards and creates the new Payment resource. A lot going on behind the scenes, but to my client code it’s as simple as writing Payment.new {...}. When the result comes back from the server, they Payment object is populated with all the relevant info (accepted/declined, reasons, etc). Basically, I’m thinking that it’s just stupid not to write web apps without a RESTful focus. It’s so easy and you get so much for free.
by rick on 13 Jan 15:20
Pat – that seems like a very common use for ARes. I’d like to see some open source CC gateway using ActiveMerchant at some point…
by Marius Mathiesen on 13 Jan 15:21
Rick: this is excellent stuff! I just had to have a look at your profile (User.find(1)) and play copycat … haven’t had this much fun since … I don’t know when. Really looking forward to the next parts… Marius
by josh on 13 Jan 15:21
Very cool. I appreciate you taking the time to write these kinds of articles. They really help me keep up with what is coming down the line in rails.
by Cameron Booth on 13 Jan 15:22
Hi Rick, Agreed with Josh, thanks for doing these. Just played around with a few posts to Beast, it’s very cool! As I’m still somewhat new to Ruby, just wanted to let you know I’m learning a lot from looking at your code these days…thanks!! Cameron
by bb on 13 Jan 15:22
Hi everyone, Dumb noob question (sorry): So am I right when I say that the big picture here with ARes is that we can make more simple, specialized apps that can then talk to each other if there is a need to exchange functionality or information (both with each other and the rest of the world)? I was reading something about django “projects” being composed of many “apps” that work together while staying modular and having specific tasks. I thought that was cool. Does ARes kind of provide a similar kind of resolution in rails? Is it practical to use ARes as the glue between separate more focused apps (sometimes even seamlessly mixin in other peoples apps or offering yours to the public through an API). Would it be a performance bottleneck most of the time if it was used alot? Could you say… build serveral apps that all do specific stuff and a user could sign up for each of the apps individually; then have an “umbrella” app that would be kind of like a “suit” and would just pull functionality out of the individual smaller apps etc. Or is that stupid? Sorry, maybe I should have waited for your next installment, Rick. At any rate thanks for writing this up! I cant wait for more!
by Rahsun Mcafee on 13 Jan 15:22
Heck YEAH! Nice post Rick. I agree with Pat in saying that I don’t think REST (thinking) has a lot of exposure and a lot of people don’t see the true power of it. Articles like this are what help push forward understanding and ideals that allow us all to interact with each other and our code more efficiently. Thanks!
by Nigel Thorne on 13 Jan 15:22
bb, I would expect things to be more service oriented. If you can see parts of the functionality that seem to be shared between apps, then they are good candidates for a service. In the example you mentioned you could factor out the login aspect as a seperate authentication service (read restfull app). This would allow your users to share username and password across all your apps. If you then provided a suit to tie your apps together, you would only have one login for the whole suite.
by bb on 13 Jan 15:22
Thanks Nigel! That helps.
by Duncan Ponting on 13 Jan 15:23
Again, thanks Rick for this. Something that I still am interested in hearing about is the handling of joins in the ARes world. So we have a app that has user info and stuff a user has written for example. In the current ARec world we can do
User.find_by_name('dave').stories, and we know that a bit of SQL is built and because there is a foriegn key in one of the tables we can get the data back from both sources. Is the thinking that ARes would also be able to do this with users being in one app and storied being in another in the future and how is the “foriegn key” thing going to be managed?by rick on 13 Jan 15:23
Duncan: Look at Beast. It has queries like /forums/1/topics that does basically the same thing. As far as ActiveResource is concerned, it makes an HTTP request, passing on an xml payload if necessary, and expects a response. Anything having to do with databases or foreign keys is handled by the actual app.
by Antonio Eggberg on 13 Jan 15:23
Rick, Do you have any documentation around acrive resources..Either I am blind or I can’t find anything on Edge rails doc at caboo.se. Any help on more info so that I can also give it a try.. as you mentioned you want more folks to use it..correct?
by goldfish on 13 Jan 15:24
Rick – good to see ActiveResource getting some attention! There’s a lot of talk about using ActiveResource to ‘share data between apps’ but I can’t quite see how to make it work smoothly. I’m wondering if there’s a way to have class User < ActiveResource::Base self.site = ‘http://localhost:30000/’ end class Post < ActiveResource::Base self.site = ‘http://localhost:40000/’ end and ‘join’ between them so that in my client I can do ‘Post.find( 1 ).user.name’...?
by Robert on 13 Jan 15:24
Rick, this is a great intro to AR – much appreciated! Looking forward to future posts about this subject.
by rick on 13 Jan 15:24
Antonio: you can build them from source with
rake rdoc. goldfish: ARes is in its infancy. Right now all it does is pulls in xml data into a format that’s easier to work with.by Antonio Eggberg on 13 Jan 15:24
Rick: Thanks for the update. I am sorry I am still stuck. I am trying to build your blog post into an rails app (as a learning purpose) but I am not having much luck. Do you happen to have anything of such simple active resource app handy? The goal is to consume an external XML file like you are doing with beast. Another blog post with an active resource app would be very very and I mean very nice! Thanks again!
by rick on 13 Jan 15:24
Yes, I have a great app that’s used by a lot of folks, only 650 lines, with 1.9 test/code ratio.
by goldfish on 13 Jan 15:26
Rick
- it’s cool that ActiveResource is still so fresh :) from where you’re standing can you tell if it’s headed towards being a full o/r(esource) mapper like ActiveRecord?by Antonio Eggberg on 13 Jan 15:27
Hi Rick! Thanks for the pointer. I have downloaded and played around with Beast! It was easy to install except the Redcloth gem (which i didn’t have) Really nice Forum! You could use a bit more Ajax i.e. forum creation.. I love the small AJAX tid bits here and there.. Now to my next question ..
1. I don’t think that active resource i.e. client side support “port numbers” i.e. 3000 or 8080 etc.
2. Any timeplan/roadmap when you might be making it a gem?
3. Do you any REST:Client based on active resources? Any inputs
thanks for your help. If you prefer I could post questions to beast.. I am thinking of playing around with beast more.
Cheers
by goldfish on 13 Jan 15:28
Hi again Rick, your article really has fired me up back up on ActiveResource :-) Just starting to toy with trying to use ARes to build a client library for an existing, non-Rails REST api. Can you recommend a good forum to discuss any design decisions involved…?
by rick on 13 Jan 15:28
Try the rails-core list I suppose. Keep in mind, it’s more for development on the framework, not questions about using it.
by rick on 13 Jan 15:28
Antonio: It does support port numbers. Just set them in the url… http://foo.com:3000/foos/:foo_id
by josh on 13 Jan 15:28
Yesterday I watched DHH’s keynote (http://www.scribemedia.org/2006/07/09/dhh/) from earlier this year for the first time. It really highlighted the elegance of CRUD in a way that I never really appreciated before. I’d highly recommend it for anyone who hasn’t seen it and finds AR intriguing.
by Adam on 11 Feb 07:55
hey rick, keep up the good work man. This article was great as an introduction to AR. i look foward to the next installment.
by no_more_koolaid on 04 Apr 20:25
umm, the user/password functionality is not in the actual rails code.
You have to hunt down and apply a patch if you want it. Color me oh so surprised that yet again using the wonderful time-saving super-dooper rails productivity actually involved extensive googling and wading through code.
by Eloy Duran on 31 May 05:21
First of all, thanks for the splendid demo Rick!
Second, with the current version of ActiveResource the above examples won’t all work. The thing is that you need to put any parameters inside it’s own params hash.
So if we look at the example: t = Topic.find 1, :forum_id => f.id
This should now be written as: t = Topic.find 1, :params => { :forum_id => f.id }
Cheers, Eloy
by AAS on 22 Jun 10:54
f63o99 Hey, there is what you need.
by ZoneWeb on 30 Jul 17:45
Hello! i found FREE xbox and iphone on the freestuffes.com, it is real??!
by BabyLawl on 12 Aug 16:04
heey!!:) I want to find the sexy boys! Im just a nice girl looking for a nice guy!:)
see my profile sugar baby
by Ojjzzxxccvvrr on 03 Nov 11:51
Tramadol is a synthetic, centrally acting analgesic agent with 2 distinct, synergistic mechanisms of action, acting as both a weak opioid agonist and an inhibitor of monoamine neurotransmitter reuptake. The 2 enantiomers of racemic tramadol function in a complementary manner to enhance the analgesic efficacy and improve the tolerability profile of tramadol. In several comparative, well designed studies, oral and parenteral tramadol effectively relieved moderate to severe postoperative pain associated with surgery. Its overall analgesic efficacy was similar to that of morphine or alfentanil and superior to that of pentazocine. Tramadol provided effective analgesia in children and in adults for both inpatient and day surgery. Tramadol was generally well tolerated in clinical trials. The most common adverse events (incidence of 1.6 to 6.1%) were nausea, dizziness, drowsiness, sweating, vomiting and dry mouth. Importantly, unlike other opioids, tramadol has no clinically relevant effects on respiratory or cardiov ascular parameters at recommended doses in adults or children. Tramadol also has a low potential for abuse or dependence. CONCLUSIONS: The efficacy of tramadol for the management of moderate to severe postoperative pain has been demonstrated in both inpatients and day surgery patients. Most importantly, unlike other opioids, tramadol has no clinically relevant effects on respiratory or cardiovascular parameters. Tramadol may prove particularly useful in patients with poor cardiopulmonary function, including the elderly, the obese and smokers, in patients with impaired hepatic or renal function, and in patients in whom nonsteroidal anti-inflammatory drugs are not recommended or need to be used with caution. Parenteral or oral tramadol has proved to be an effective and well tolerated analgesic agent in the perioperative setting. tramadol tramadol cod tramadol hcl tramadol 180 tramadol hydrochloride buy tramadol cheap tramadol buy tramadol online tramadol online cod tramadol tramadol side effects
by Ojjzzxxccvvrr on 03 Nov 11:51
Tramadol is a synthetic, centrally acting analgesic agent with 2 distinct, synergistic mechanisms of action, acting as both a weak opioid agonist and an inhibitor of monoamine neurotransmitter reuptake. The 2 enantiomers of racemic tramadol function in a complementary manner to enhance the analgesic efficacy and improve the tolerability profile of tramadol. In several comparative, well designed studies, oral and parenteral tramadol effectively relieved moderate to severe postoperative pain associated with surgery. Its overall analgesic efficacy was similar to that of morphine or alfentanil and superior to that of pentazocine. Tramadol provided effective analgesia in children and in adults for both inpatient and day surgery. Tramadol was generally well tolerated in clinical trials. The most common adverse events (incidence of 1.6 to 6.1%) were nausea, dizziness, drowsiness, sweating, vomiting and dry mouth. Importantly, unlike other opioids, tramadol has no clinically relevant effects on respiratory or cardiov ascular parameters at recommended doses in adults or children. Tramadol also has a low potential for abuse or dependence. CONCLUSIONS: The efficacy of tramadol for the management of moderate to severe postoperative pain has been demonstrated in both inpatients and day surgery patients. Most importantly, unlike other opioids, tramadol has no clinically relevant effects on respiratory or cardiovascular parameters. Tramadol may prove particularly useful in patients with poor cardiopulmonary function, including the elderly, the obese and smokers, in patients with impaired hepatic or renal function, and in patients in whom nonsteroidal anti-inflammatory drugs are not recommended or need to be used with caution. Parenteral or oral tramadol has proved to be an effective and well tolerated analgesic agent in the perioperative setting. tramadol tramadol cod tramadol hcl tramadol 180 tramadol hydrochloride buy tramadol cheap tramadol buy tramadol online tramadol online cod tramadol tramadol side effects
by Vjhoncruut on 25 Nov 03:34
Create a list of your mp3’s. Include info of your choice (size, time, bitrate, stereo mode, path, date, etc). Save in internal format or export as text, html or xls. Import lists created by other applications. Find duplicates in your list. Compare your list to other people’s lists (find out what others have that you don’t, and the opposite). Insert & edit items. Plenty options to satisfy almost anyone
download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music download mp3 music download music mp3 music download mp3 mp3 music download mp3 download music
by indipsanaback on 18 Dec 11:45
Hi buddie suicide bomber
by indipsanaback on 18 Dec 11:45
Hi buddie suicide bomber
by indipsanaback on 18 Dec 11:45
Hi buddie suicide bomber
by indipsanaback on 18 Dec 11:46
Hi buddie suicide bomber
by BeesAccenty on 21 Dec 02:29
hi, i sure it About cake recipes
by LiaroCowerene on 21 Dec 15:07
http://www.google.com http://www.yahoo.com http://www.msn.com
by Extefearady on 05 Jan 09:55
What an substantial post, but I think differently. Extrefox
by Gymnillency on 05 May 12:34
Ambien without prescription overnight delivery Buy tramadol cash on delivery Order tramadol cod Buy soma cod Phentermine next day delivery Order tramadol online without prescription. Valium next day delivery Ambien no prescription overnight delivery Buy phentermine cash on delivery Order valium cash on delivery Buy ultram cod Buy ambien without prescription Buy soma no prescription Buy tramadol online Buy viagra cash on delivery Buy tramadol cod Buy ultram cash on delivery Propecia online without prescription