· 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):

123~
</td>
class MyClass < ActiveResource::[.co]Base  self.site = [.dl]"[.k]#http://localhost:3000/[.dl]"[.r]#end~
</td>
</tr>
</tbody></table>
And then called this class as follows:
1~
</td>
MyClass.create(:param => [.dl]"[.k]#param-value[.dl]")~
</td>
</tr>
</tbody></table>
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:
12345678~
</td>
[.r]#class MyClass < ActiveResource::[.co]Basedef instance(site, args)  self.site = site  new(args) unless args.nil?endend~
</td>
</tr>
</tbody></table>
We then call the code like this:
12~
</td>
my_class = MyClass.instance([.dl]"[.k]#http://localhost:3000[.dl]", [.sy]:param# => [.dl]"[.k]#param-value[.dl]#")my_class.save~
</td>
</tr>
</tbody></table>
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