Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ActiveRecord interface for Models backed by external API in Ruby on Rails

I'm trying to use Models in my Rails application that retrieve information from an external API. What I would like to do is access my data models (which may consist of information resulting from multiple API calls) in a way similar to what an ActiveRecord model would provide (specifically associations, and the same style of chain-able query methods).

My initial instinct was to recreate the parts of ActiveRecord that I wanted and incorporate this API. Not wanting to 'reinvent the wheel' and seeing exactly how much work would be required to add more functionality have made me take a step back and reevaluate how to approach this.

I have found ways to use ActiveRecord without a table (see: Railscast #193 Tableless Model and the blog post here) and looked into ActiveRecord. Because ActiveModel only seems to include Validations I'm not sure that's very helpful in this situation. The workaround to using ActiveRecord without a table seems like the best option, but I suspect there's a cleaner way of doing this that I'm just not seeing.

Here is a gist containing some of the code written when I was trying to recreate the ActiveRecord functionality, borrowing heavily from the ActiveRecord source itself.

My question boils down to: I can get the functionality I want (chaining query methods, relations) by either implementing the workaround to ActiveRecord specified above or recreating the functionality myself, but are these really ideal solutions?

like image 535
Chris Hunt Avatar asked Mar 09 '13 17:03

Chris Hunt


1 Answers

Remember that Rails is still just Ruby underneath.

You could represent the external API as instantiated classes within your application.

class Event
  def self.find(id)
    #...External http call to get some JSON...#
    new(json_from_api)
  end

  def initialize(json)
    #...set up your object here...#
  end


  def attendees
    #...external http call to get some JSON and then assemble it 
    #...into an array of other objects
  end
end

So you end up writing local abstractions to create ruby objects from api calls, you can probably also mix in ActiveModel, or Virtus into it, so you can use hash assignment of attributes, and validations for forms etc.

Take a look at an API abstraction I did for the TfL feed for the tube. service_disruption

like image 167
Adam Carlile Avatar answered Oct 03 '22 00:10

Adam Carlile