Answer the question
In order to leave comments, you need to log in
Is it possible to create a Model in Ruby on Rails with a data source as an external RESTful API?
Silly question, perhaps, but still.
A model in RoR is a description of an entity in a database (as I understand it).
In the model file, you can create your own methods that will make direct queries to the database and return collections of data.
In my project, I get data not from a database, but from an external RESTful API.
Is it possible (without crutches) to build my implementation of this API into the model?
Below is an idea, not a real implementation.
# controller.rb
def Controller
Users.all
end
# model.rb
def Model
def all
HTTPClient.get 'https://example.com/users.json'
end
end
Answer the question
In order to leave comments, you need to log in
There is a problem with the approach you propose, in that your project will depend almost entirely on this data source.
Maybe you could do the following:
You can write a job that will connect to this data source for some period of time (once an hour or once a day), collect them in a bunch as you need and send them to your database on your server .
In fact, just not a permanent connection to a remote data source.
This could be convenient if the data source is not yours and you cannot influence it (it will fall for example)
But at the same time, if it is important for you to process data in real time (the user has registered and information about him has gone to this remote server, and after registration you immediately need this data - to check the login and password when logging in, for example), this approach will not work
here you need to know more about the subject area, maybe if you just need to fill your model with data once, then it would be most convenient to implement this somewhere in the migration in general.
Well, make a wrapper like this:
module GetUsers
def all
ApiClient.new.all
end
end
class User
extend GetUsers
end
users = UserService.new.all
There is a special gem https://github.com/remiprev/her
Met a couple of years ago in a project, quite convenient. But, there the guys got confused and added a little code so that there was no difference at all where you had the data and you could use both regular models and these with standard constructions. All relationships and more worked
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question