Best practice of implementing a webservice client in rails application - ruby-on-rails

In situation, when I need a webservice client, which will be used by some action controllers, how should it be implemented? As it will have some constant values (addres, parameters names) and session key, refreshed every 30 minutes, I guess model stored in database isn't the best solution. What is the best practice?

Built the web service consumer as a library and place it in your /lib directory.
I would also recommend HTTParty for very simple consumption of web services. You could easily build a library to handle the task, a simple class with a few methods and toss it in your /lib directory and be on your way.
Good luck!

Rails 1.x used to have "actionwebservices" builtin but it has been removed from Rails 2.x. The last time I did this was to build an SSO server implemented as classes using XML-RPC. The code is not public unfortunately (done internally for my employer) but was under 1k LOC incl. comments... Plain Ruby.
Now, I'd probably use a lightweight framework like Sinatra or an equivalent.

Related

What would be the best way to use AngularJS with Ruby on Rails?

I'm about to start a new project and I am unsure if using AngularJS for my front end would be a good idea not. I've read about people saying this isn't the smartest way of doing a project. And even if I did, Is there a way to get AngularJS to interact with the controllers? This question may be redundant but I am actually curious of how to effectively do this without it being a waste of time.
I've never completely done it, but I believe the way to go is to build a Rails api and then have a separate Angular project use said api. The api could also be used to build a mobile app. I think the Angular project would still need to be served from a Node.js server in production, but I don't think that would be a big deal.
This is what I used to learn how to build a Rails api: http://apionrails.icalialabs.com/book/chapter_one
You can do it within an existing project and share the models from it.
There are several different approaches to accomplish that. I tried about 5 different guides out there, the best I found (and I finally sticked to) was https://thinkster.io/angular-rails - This guide should help you build a basic CRUD app with angular connected to rails.
You use Rails as an JSON RESTful API which responds to Ajax-Requests (Get, Post, Put, Delete). Angular will handle the frontend stuff - sending those Ajax requests to the routes/methods defined in your rails controllers. So yes, of course your AngularJS app can interact with your rails controllers.
This also helped me to understand the setup in the beginning: Instead of the Rails View, you will be using AngularJS as your view:
I really love using angular with rails, because setting up the JSON responses (especially with Active Model Serializer Gem) is very easy and quickly done. i deffinitely can recommend it, and I have not encountered any unsolvable problems - so far.
Just go trough this guide I linked and you will see if this setup fits your needs.
The short answer is that your Rails application will have to present some kind of a public API for your AngularJS application to consume. Angular (and it's brethren, like React and Ember) runs client-side, on the browser, and it needs "something" to make AJAX calls against. That "something", i.e. your backend, can be Firebase, Parse, AWS Lambdas, Rails API, etc. Since you already have a Rails application, it probably makes the most sense to add some RESTful API endpoints that use the existing models (and possibly controllers) to consume/produce JSON payloads from/for the client.

Organize External API Calls in Rails 4 - Module or Class?

I am creating a Rails app that will use quite a few external APIs such as SalesForce, FolderGrid(like Dropbox) etc., which would all sync to my database. I've never worked with external api calls so I created a few basic Ruby scripts with scattered methods to test the call to those resources. Now I would like to implement them with my full Rails app.
So far, I started off by creating a directory in my /lib folder for holding the api call modules/classes..
/lib/apis/foldergrid.rb
Now I'm not sure what the best approach would be towards organizing the code. In my standalone Ruby scripts, I have methods for authenticating, creating a folder, auditing files, downloading files etc.
What should be in a Module? Do I even need a Module? What should be in a class? How do I make sure I can use these methods in my models and controllers where needed? Is there a best practices concerning external APIs?
Any resources, links, and/or deeper understanding is highly appreciated.
I have an app that does this too (pulls data from multiple APIs) so I can tell you what I would did (or in some cases what I would do now if I was to start over).
Data Storage
First off if you are already persisting the data pulled from those into a Rails app, then you will have models representing the data themselves. So that's what you would refer to in your controllers unless your controller is in charge of calling the APIs.
Use Gems where possible
Second make sure to leverage existing gems that existing for the APIs so you're not recreating the wheel of authentication, parsing the JSON to and from the app, etc. For example: there is a rest-force gem for salesforce.
Use Ruby Objects in Lib for mapping between your models and API responses
Third, I would make the classes that map data in between API responses and your models into "Plain old ruby objects" and store them in a lib/apis folder (no need in these cases to store in a module, yet IMHO). They might end up very functional and in the case of mapping data, that is ok.
APIs without existing Gems
In those cases, I would definitely keep them in one or more classes under a module, in their own folder in lib. That way you can parse them out if needed as a Gem (or if you to take the time make them a Gem to start with, I'm sure others could benefit). I just started down this road myself this week using Infoconnect's API which didn't have a Gem (or any code samples in any language). But I'm not very far along.
If needed, create service objects for code in between V and C (view and controllers)
If you do end up needing to do anything to interact with users for the API information or anything that calls those request, I would put those in service objects so your code doesn't get bloated in the view or controller.
What should be in a Module?
A module should contain code that is shared by different classes, or it can be added to a single class.
Do I even need a Module?
No, you can achieve the same thing with inheritance. If there is no code to share, then you probably don't need a module.
How do I make sure I can use these methods in my models and controllers where needed?
You can access them using the class from within a controller:
SalesForceAPI.get_data
"Module or class?" is an age-old question in Ruby, and any other language that supports both.
I would encapsulate the functionality for each API in a class. For example, you can have a SalesForceAPI class. Then, if you need to share functionality between the classes for authenticating, creating a folder, auditing files, or downloading files, you can create an API class.
Each of the classes that needs access to the API class would inherit from it:
SalesForceAPI < API
You can achieve the same thing by creating an API module, and mixing it into the other classes. In this case, it's largely a matter of preference, because either solution is good.
FWIW, I don't know if there would be much shared functionality for authenticating, creating a folder, auditing files, or downloading files, because each API can work quite differently. However, if they are REST API's then you may create some REST helper methods and put them in the API class.
A great, easy to understand, and complete resource on the topic is Practical Object Oriented Design Ruby.

Rails app with non-HTTP access

Hypothetical question (at the moment!)
Suppose I have a great idea for an application. It acts on data which can be well-represented by tables in a relational database, using interlinked objects which represent those tables. It supports a well-defined API for interacting with (Creating, Reading, Updating, Deleting) those objects, and viewing information about them.
In short, it's a perfect fit for Rails... except it doesn't want to be a web-app. Perhaps it wants a Command Line interface; or an OS-native dialog-based interface; or perhaps it wants to present itself as a resource to other apps. Whatever - it just isn't designed to present itself over HTTP.
These questions suggest it's certainly possible, but both approach the problem from the point of view of adapting an existing web-app to have an additional, non-web, interface.
I'm interested in knowing what the best way to create such an app would be. Would you be best to rails new non_web_app, in order to get the skeleton built "for free", then write some "normal" Ruby code that requires config/environment - but then you have a lot of web-centric cruft that you don't need? Or would it be better to roll up your sleeves and build it from whole cloth, taking just the libraries you need and manually writing any required configuration?
If the latter, what exactly is needed to make a Rails app, but without the web bits?
If you want to access the Rails ORM to develop a CRUD non-web application, just include ActiveRecord in your own Ruby script; you will avoid using a lot of Rails modules you probably don't need (routing, template generator, ...) Here is an example of how to do it.
If you prefer to have the full Rails stack, do not run your Rails web app in an application server (WEBrick, Passenger, Mongrel, ...) to avoid any HTTP exposure, and interact with your application using tasks or the rails console.
I would avoid taking Rails too far off the rails. If I were doing this and felt that the gains of rails w/o the web stuff I'd do the following:
rails new non_web_app
and ignore the webbish cruft and use rails to generate models. In this way you get the tight, comfortable database behavior and can tie various gems in as you want to augment those models. I'd not bother implementing views, of course, and I'd consider implementing controllers in which the various render bits are removed and to use you instantiate an instance of the controller and call the action directly. This means the controller represents your API into your business logic still but the "views" it now "renders" are simply the return of the data output.
Then you could simply strip out the bits you do not need...the public directory, the view structure under app, config/routes.rb, etc. You'll need to test those changes incrementally and make sure that removing some now extraneous bit doesn't throw the Rails world into chaos.
Rails is for Web apps. That means HTTP. Now, you could package a Web app so that it runs on the desktop instead, or you could use ActiveRecord with a desktop application framework like Monkeybars.

What's the best way to integrate a Django and Rails app sharing the same MySQL datastore?

I'm going to be collaborating with a Python developer on a web
application. I'm going to be building a part of it in Ruby and he is
going to build another part of it using Django. I don't know much about
Django.
My plan for integrating the two parts is to simply map a certain URL
path prefix (say, any request that begins with /services) to the Python
code, while leaving Rails to process other requests.
The Python and Ruby parts of the app will share and make updates to the
same MySQL datastore.
My questions:
What do people think generally of this sort of integration strategy?
Is there a better alternative (short of writing it all in one language)?
What's the best way to share sensitive session data (i.e. a logged in
user's id) across the two parts of the app?
As I see it you can't use Django's auth, you can't use Django's ORM, you can't use Django's admin, you can't use Django's sessions - all you are left with is URL mapping to views and the template system. I'd not use Django, but a simpler Python framework. Time your Python programmer expanded his world...
One possible way that should be pretty clean is to decide which one of the apps is the "main" one and have the other one communicate with it over a well-defined API, rather than directly interacting with the underlying database.
If you're doing it right, you're already building your Rails application with a RESTful API. The Django app could act as a REST client to it.
I'm sure it could work the other way around too (with the rest-client gem, for instance).
That way, things like validations and other core business logic are enforced in one place, rather than two.
A project, product, whatever you call it, needs a leader.
This is the first proof that you don't have one. Someone should decide either you're doing ruby or python. I prefer ruby myself, but I understand those who prefer python.
I think starting a product asking yourself those kind of questions is a BAD start.
If your colleague only knows prototype, and you only know JQuery, are you going to mix the technologies too? Same for DB? And for testing frameworks?
This is a never ending arguing subject. One should decide, IMHO, if you want so;ething good to happen. I work with a lot of teams, as a consultant, Agile teams, very mature teams for some of them, and that's the kind of stuff they avoid at all cost.
Except if one of you is going to work on some specific part of the project, which REALLY needs one or other of the technologies, but still think the other one is best for the rest of the application.
I think, for example, at a batch computing. You have ALL your web app in ror or django, and you have a script, called by CRON or whatever, computing huge amounts of data outside the web app, filling a DB or whatever.
My2Cts.

Rails-The best way to use external SOAP API?

I am developing a Rails application which will need frequent access to public APIs, and I am not sure what is best way to put external API (SOAP/WSDL) code in Rails application, what about model thingy, how we can manage that? Any ideas, comments?
The current contenders for "best" library for consuming External SOAP services seems to be either Savon or Handsoap. There is a comparison between the two here
I can't comment on handsoap as I haven't used it by I am happy with Savon which is working well for me.
In terms of Application structure then I would create a folder under lib for the interface named after the external entity and then store files under there using the namespacing features of rails.
So an example I have an external interface to a system called Sentinel. So I have RAILS_ROOT/lib/sentinel and then all classes within that folder are declared within a Sentinel module.
The first thing to do would be to see if there are any gems for the API's you want to interface with. Write a small wrapper class for the gem or just include it and use it where needed.
If you're looking to talk to a REST service, I would suggest the rest-client gem. If you want to do something completely custom you could make use of Jon Nunemaker's HTTParty. Nokogiri, an XML parser gem is useful for consuming XML-based services as well.

Resources