Q:

Ruby on Rails posting to an API using javascript via a proxy

I'm very new to Ruby on Rails and I'm hoping this will be a quick fix. I have a very simple form (firstname, surname, email) that needs to post XML to an API on another domain. Everything on our site is clientside javascript so I would like to post to a proxy within our Rails app to get over the cross-domain issue.
I found this bit of code, that seems to be doing what I want - https://github.com/bitzesty/xml2jsonp but I have no idea how and where to install this in our Ruby app so I can post to it and receive the response.
Any help would be appreciated.

A:

Net::HTTP is Ruby's built in library for sending HTTP requests. Rails also has built in features for serializing models to XML.
Lets say you bind your form to a User model:
class User < ActiveModel::Base
  # attr_accessor is not needed if these are real DB columns.
  attr_accessor :firstname
  attr_accessor :surname
  attr_accessor :email
end

And handle the form in UsersController#create
def UsersController < ApplicationController
  # POST `/users`
  def create
    @user = User.new(user_params)
    # @todo send user to remote service.
  end

  def user_params
    params.require(:user).permit(:firstname, :surname, :email)
  end
end

We can then create a service object that posts the user to the remote API
# app/services/user_posting_service
class UserPostingService

  attr_accessor :user
  attr_accessor :client

  # Passing in the client lets us easily stub Net::HTTP in tests
  def initialize(user, client = Net::HTTP)
    @user = user
    @client = client
  end

  def call
    uri = URI('http://www.example.com/user.cgi')
    req = Net::HTTP::Post.new(uri)
    # see http://apidock.com/rails/ActiveRecord/Serialization/to_xml for options.
    req.body = @user.to_xml 

    res = Net::HTTP.start(uri.hostname, uri.port) do |http|
      http.request(req)
    end

    case res
    when Net::HTTPSuccess, Net::HTTPRedirection
      true
    else
      false
    end
  end
end

We can then use the service in our controller:
def UsersController < ApplicationController
  # POST `/users`
  def create
    @user = User.new(user_params)
    @posted = UserPostingService.new(@user).call
    if @posted
      # ... 
    else
       # ... 
    end
  end
  # ...
end

There are several steps which are not included for brevity: 

You need to create a route for users#create
If you want post the form with ajax you need to setup a handler in javascript. You should also setup the controller to respond with JSON.
You may need to set the content-type and other headers depending on the external API.
You may need to authenticate the request to the external API.

Both of these are pretty basic Rails skills and if you do not know how to get it done you should follow a tutorial or read a book before trying more advanced tasks.

