Using JSON as a Rails Model

How can I use the JSON service as a model for a Rails 3.2 application?

I would like to associate model methods with JSON requests, for example

  • MyModel.create to create a JSON request to create a new record
  • MyModel.find to create a JSON request to retrieve a record and decode a JSON response into a model object

What is the preferred way to create this type of functionality? One of the options I'm looking for is to create a custom DataMapper adapter.

Thanks.

Update:
Please note: I cannot use ActiveResource, because this requires the JSON service to respond in a specific way, which is not the case.

+6
source share
5 answers

Short answer: it depends on your JSON service.

Is a RESTful service for starters? If so, you're in luck. ActiveResource is dead , so I would not recommend using it, but the code itself would provide a good starting point for creating a set of wrapper methods, such as create and find to access your API and manage records, as ActiveRecord creates and queries records in the database. This is relatively easy if your API is RESTful, because the rails are built around RESTful-ness , so matching between them becomes much cleaner.

This article sums up well:

Rails makes it easy to create web services that follow REST principles and work equally well with web browsers and programmable Web. In fact, this simplicity comes directly from these principles. We were not supposed to tell our client how to create, read, update, or delete a resource, all of which follow the use of proper HTTP methods. All we had to do was point our client in the right place.

If your service is not RESTful, which, judging by the comments on other issues, I think it is possible, then you will have your own job for you. ActiveModel will not do the job for you: create is defined in ActiveRecord :: Persistence and find is defined in ActiveRecord :: FinderMethods . They are not in ActiveModel. ActiveResource is able to reproduce them quite easily because it makes assumptions about the type of service it interacts with (i.e., it is RESTful, plus a few other things).

What ActiveModel offers is all that makes rails so useful for working with models: its verification system, serialization methods, dirty tracking of attribute changes, callbacks ( before_save , after_save , etc.), translation / localization, etc. These are all very useful features, but they still leave you with the problem of wrapping API calls.

So, here is what I would recommend based on my, albeit limited, experience (see my last note on this):

  • First, read your API carefully and find out how close it is to RESTful. If this is not RESTful, you will have to think about how to get around this so that you can consider it as a RESTful service. A good reference to how to do this is O'Reilly RESTful Web Services (in particular, Chapter 2, โ€œWriting Web Service Clientsโ€.)
  • Create an API wrapper around it that implements create , find and any other functions like ActiveRecord that you want to use. You probably want to use a gem like Faraday or HTTParty for actual API requests, rather than working directly with Net :: HTTP. (I have never used DataMapper, so I can not comment on this.)
  • Include any ActiveModel elements that you want to use to make your wrapper class look more like a rail model: checks, serialization, etc. In Rails 4, you can actually enable everything using the new barebones ActiveModel :: Model .

This will help you use the JSON service as a Rails model.

For the record, my experience in implementing these kinds of things is limited to creating an API wrapper (in my works) for accessing the XML API. The shell has a class that includes ActiveModel validators for validating API requests. I found that ActiveModel validators are really useful for ensuring proper API access, but the shell is only for retrieving entries from the API, not for actually creating or updating them, so the interface is much simpler than I expect you to build.

+3
source

I think you are looking for ActiveResource , you can use it instead of ActiveRecord to work with the RESTful JSON API, see this link and this (apidock)

+1
source

The best way to do this is to implement ActiveModel. This railscast covers the basics.

+1
source

I only do this in my otrs_connector gemstone ... It wonโ€™t work for your service, but it can give you an idea on how to do it ... The approach I took may not be the best, and it needs a little reorganize, but it works, and it is very good.

0
source

If the web service is outside the normal Rails path, I would recommend HTTParty . It is very easy to make a proxy web service that responds as you want.

For example, here is their example of accessing the Twitter timeline

 class Twitter include HTTParty base_uri 'twitter.com' def initialize(u, p) @auth = {:username => u, :password => p} end # which can be :friends, :user or :public # options[:query] can be things like since, since_id, count, etc. def timeline(which=:friends, options={}) options.merge!({:basic_auth => @auth}) self.class.get("/statuses/#{which}_timeline.json", options) end def post(text) options = { :query => {:status => text}, :basic_auth => @auth } self.class.post('/statuses/update.json', options) end end twitter = Twitter.new(config['email'], config['password']) pp twitter.timeline 
0
source

Source: https://habr.com/ru/post/922003/


All Articles