· ruby rails rest activeresource

Ruby: Parameterising with ActiveResource

We’ve been using Ruby/Rails on my current project to create a RESTful web service. One of the problems we wanted to solve was making the data queried by this web service configurable from our build.

We started off with the following bit of code (which makes use of the recently added ActiveResource class):

1
2
3
~~~
class MyClass < ActiveResource::Base
  self.site = http://localhost:3000/
end~~~
And then called this class as follows:
1
~~~
MyClass.create(:param => param-value)
~~~
This worked fine for us until we wanted to parameterise the ‘site’ value so that we could set it to different values depending which build we were running (dev/ci/qa). We tried all the obvious ways - overriding the constructor and passing in the site, trying to set the site by calling MyClass.site but none of them did what we wanted. We eventually ended up creating a new method to create an instance of the class with our configurable site:
1
2
3
4
5
6
7
8
~~~
class MyClass < ActiveResource::Base

def instance(site, args)
  self.site = site
  new(args) unless args.nil?
end

end
~~~
We then call the code like this:
1
2
~~~
my_class = MyClass.instance(http://localhost:3000, :param => param-value)
my_class.save~~~
It seems like a bit of a hack but it got it working!

Out of interest it has taken me ages to try and find a way to put the Ruby code on here in a readable format. I tried to use the TextMate exporter but that wasn’t giving me any love. I eventually ended up using Spotlight, a neat little tool written by Tyler Jennings. I found it from Jake Scruggs blog post.

  • LinkedIn
  • Tumblr
  • Reddit
  • Google+
  • Pinterest
  • Pocket