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

后端 未结 1 1367
长发绾君心
长发绾君心 2021-02-06 08:50

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 informat

相关标签:
1条回答
  • 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

    0 讨论(0)
提交回复
热议问题