Is there a way to set the default namespace with Savon::Model? - ruby-on-rails

Savon is stubborn in generating SOAP envelopes from WSDL's. It does it improperly and I see no way to fix it. It also takes the liberty of inserting the wsdl: namespace on everything for whatever reason.
The request I am building uses the tns: namespace. I'd love to be able to use Savon::Model, but right now I have to do:
client.request :tns, :function_name do
soap.body = { params }
end
Instead of something like:
super(params)
Making the request block in every function is tedious, and I have to define the function name every time instead of Savon automatically calling the correct function like what would happen in the ideal case. Right now my functions are looking like
def foo
client.request :tns, :foo do
...
end
Having to say "foo" twice seems ridiculous. Is there a way to set the default namespace for every request in a class that extends Savon::Model?

client = Savon.client do
wsdl "blah blah"
element_form_default :qualified
namespace_identifier :tem
env_namespace :soapenv
end

I am not sure if I understand your questions. I assume you are asking how to set the default namespace and wrap the request body in a function, so you don't need to write the request body every time. This code works for me, but I removed some irrelevant parts
class ExampleWS
EXAMPLE_WS_DEFAULT_NAMESPACE = "urn:example:request:1.0.0"
......
def getStockPrice( locale, stockId )
response = $client.request :get_stock_price do
soap.input = [
"ns1:getStockPrice",
{
"xmlns:ns1" => EXAMPLE_WS_DEFAULT_NAMESPACE #set default namespace here
}
]
soap.body = {
"locale" => locale,
"stockId" => stockId
}
end
end
......
end
......
# call the function
getStockPrice("en_US", 123 )

This works for me. It uses Savon 2, though:
class Soapservice
extend Savon::Model
client wsdl: "http://example.com?wsdl", env_namespace: :tns,
operations :get_resource, :put_resource
def :get_resource(id)
super(message: { id: id })
end
end
service = Soapservice.new
response = service.get_resource(1) #overwriting get_resource
# or
response = service.put_resource(message: { username: "luke", secret: "secret" })
(My example builds on the one from the official savon homepage)

Related

How to check header of request inside a method using Rspec?

I have a method that will hit other API. And I made a condition to decide which auth token that will be used while posting to that API. Example:
class OrderFee
def perform
get_pricing
end
private
def get_pricing
payload = {
from: "a",
to: "b"
}
authorization = ''
if Config.UsingFirstToken?
authorization = "first_token"
else
authorization = "second_token"
end
response = Connection.MyCourier.post(url, payload) do |req|
req.headers['Authorization'] = authorization
end
response.body
end
end
I want to make 2 test case using Rspec to make sure if Config.UsingFirstToken true, it will hit the API using first_token, and otherwise. I can check the return value of this method, but I can't find a way to expect header from that POST action
You have access to the request object in your spec.
Expect what the header equals like this:
expect(request.headers['Authorization']).to eq("first_token")
Or whatever you expect the token to be.

How to Consume SOAP with Savon in Rails app

I need to communicate to a service called ifthenpay via Soap using Savon on a Rails app that i'm working on.
The service generates payment references so users could pay on home banking or in cash machines.
The app needs to communicate to the service to see if the payment was made or not.
I'm using Savon and this is what i have so far in the checkout model(don't know if this is the right place to put the above code):
def self.check_status!
client = Savon.client(
wsdl: "http://www.ifthensoftware.com/IfmbWS/IfmbWS.asmx?WSDL",
endpoint: "http://localhost:3000",
namespaces: {"xmlns:ift"=>"https://www.ifthensoftware.com/"}
)
begin
response = client.call(:get_payments, message: check_status_hash)
rescue Savon::SOAPFault => error
#...
end
end
def self.check_status_hash
{
"ift:get_payments" => {
"ift:chavebackoffice" => { "ift:chavebackoffice" => "0000-0000-0000-0000" },
"ift:entidade" => {"ift:entidade" => "11202"},
"ift:subidentidade" => {"ift:subidentidade" => "202"},
"ift:dtHrInicio" => {"ift:dtHrInicio" => ""},
"ift:dtHrFim" => {"ift:dtHrFim" => ""},
"ift:referencia" => {"ift:referencia" => ""},
"ift:valor" => {"ift:valor" => ""}
}
}
end
I've an admin page where i need to list all the payments that have been made, so i can manage what was selled.
You can see the service operations here
What do i need to put in the controller and in the view for this to work?
I really appreciate your help, because i'm struggling with this for a long time.
From my point of view, and pardon me because I'm not very experienced with the use of savon, you are slightly overkilling this.
To start with, you are providing the client with a WSDL url, so what is the use of attaching a doubtfully necessary endpoint?
A namespace is, to my understanding, necessary, once again, in case there is no standard WSDl interface.
I would go, to start off, I would simply go for:
#client = Savon.client(wsdl: "http://www.ifthensoftware.com/IfmbWS/IfmbWS.asmx?WSDL")
Watch the #client instead of client. We need to assign the client to a variable that will be reachable throughout the entire process (request, process, response).
Next, you will need to prepare your request. Parsing the above url, there is a banch of methods. You are providing in your example getPayments request.
I will not use this space to tell you how to construct the hash, but the hash should look something like this:
request_hash = {
chavebackoffice: "0000-0000-0000-0000",
entidade: "11202",
subidentidade: "202",
dtHrInicio: "",
dtHrFim: "",
referencia: "",
valor: ""
}
To make the call to the api, you should simply do this:
#response = #client.call(:get_payments) do
message request_hash
end
And then, parse the #response. You will probably need to turn it to a hash first. Maybe something like this:
#data = #response.to_hash[:get_payments_response][:get_payments_result][:ifmb]
I hope this will help you enough. It should be more than enough.
Putting all up: Controller code, adapt to your need
before_action :set_client, only: [:get_payments, :other_actions_perhaps]
def get_payments
# params[:whatever] in case you post to #whatever object
# params without [:whatever] if you are using "GET" method
request_hash = {
chavebackoffice: params[:whatever][:chavebackoffice],
entidade: params[:whatever][:entidade],
subidentidade: params[:whatever][:subidentidade],
dtHrInicio: params[:whatever][:dtHrInicio],
dtHrFim: params[:whatever][:dtHrFim],
referencia: params[:whatever][:referencia],
valor: params[:whatever][:valor]
}
response = #client.call(:get_payments) do
message request_hash
end
# use this #data in your view
#data = response.to_hash[:get_payments_response][:get_payments_result][:ifmb]
end
def set_client
#client = Savon.client(wsdl: "http://www.ifthensoftware.com/IfmbWS/IfmbWS.asmx?WSDL")
end

Rspec testing inside a loop

I am trying to test the code inside a loop, how would I go about this:
class MyClass
def initialize(topics, env, config, limit)
#client = Twitter::Streaming::Client.new(config)
#topics = topics
#env = env
#limit = limit
end
def start
#client.filter(track: #topics.join(",")) do |object|
# how would I test the code inside here, basically logical stuff
next if !object.is_a?(Twitter::Tweet)
txt = get_txt(object.text)
end
end
Is there a way to do this?
If think that you can use a double of your Twitter::Streaming::Client that has a method filter and when this method is invoked it returns the desired output:
let(:client) { double 'Twitter Client', filter: twitters }
You will need to built manually the twitters object (sorry by my lack of context but I never used the Twitter client) and then you can make the assertions for the result of the start method.
As you can see, testing that code is quite tricky. This is because of the dependency on the Twitter client gem.
You can go down couple of paths:
Don't test it - the Twitter client gem should provide you with Twitter::Tweet objects. You only test your logic, i.e. get_txt method
Do what #Marcus Gomes said - create a collection double that has the filter method implemented.
What I would prefer to do is to stub the #client.filter call in the spec.
For example, in your spec:
some_collection_of_tweets = [
double(Twitter::Tweet, text: "I'll be back!"),
double(Twitter::Tweet, text: "I dare ya, I double dare ya!")
]
#my_class = MyClass.new(topics, env, config, limit)
allow(#my_class.client).to receive(:filter).and_return(some_collection_of_tweets)
This means that the some_collection_of_tweets collection will be returned every time the class calls #client.filter, and by having the data built by you, you what expectations to set.
One thing that you will have to change is to set an attr_reader :client on the class. The only side effect of this type of testing is that you are tying your code to the interfaces of the Twitter client.
But like everything else... tradeoffs :)
Hope that helps!
Perhaps you could do something like this if you really wanted to test your infinite loop logic?
RSpec.describe MyClass do
subject { MyClass.new(['foo','bar'], 'test', 'config', 1) }
let(:streaming_client) { Twitter::Streaming::Client.new }
describe '#start' do
let(:valid_tweet) { Twitter::Tweet.new(id: 1) }
before do
allow(Twitter::Streaming::Client).to receive(:new)
.with('config').and_return(streaming_client)
end
after { subject.start }
it '#get_txt receives valid tweets only' do
allow(valid_tweet).to receive(:text)
.and_return('Valid Tweet')
allow(streaming_client).to receive(:filter)
.with(track: 'foo,bar')
.and_yield(valid_tweet)
expect(subject).to receive(:get_txt)
.with('Valid Tweet')
end
it '#get_txt does not receive invalid tweets' do
allow(streaming_client).to receive(:filter)
.with(track: 'foo,bar')
.and_yield('Invalid Tweet')
expect(subject).not_to receive(:get_txt)
end
end
end

Problems with MailChimp API in Ruby Error Code: -90

I am using the following code in my MailChimp Controller to submit simple newsletter data. When It is sent I receive the following error as a "Method is not exported by this server -90" I have attached my controller code below. I am using this controller for a simple newsletter signup form. (Name, Email)
class MailchimpController < ApplicationController
require "net/http"
require "uri"
def subscribe
if request.post?
mailchimp = {}
mailchimp['apikey'] = 'f72328d1de9cc76092casdfsd425e467b6641-us2'
mailchimp['id'] = '8037342dd1874'
mailchimp['email_address'] = "email#gmail.com"
mailchimp['merge_vars[FNAME]'] = "FirstName"
mailchimp['output'] = 'json'
uri = URI.parse("http://us2.api.mailchimp.com/1.3/?method=listSubscribe")
response = Net::HTTP.post_form(uri, mailchimp)
mailchimp = ActiveSupport::JSON.decode(response.body)
if mailchimp['error']
render :text => mailchimp['error'] + "code:" + mailchimp['code'].to_s
elsif mailchimp == 'true'
render :text => 'ok'
else
render :text => 'error'
end
end
end
end
I highly recommend the Hominid gem: https://github.com/tatemae-consultancy/hominid
The problem is that Net::HTTP.post_form is not passing the "method" GET parameter. Not being a big ruby user, I'm not certain what the actual proper way to do that with Net::HTTP is, but this works:
require "net/http"
data="apikey=blahblahblah"
response = nil
Net::HTTP.start('us2.api.mailchimp.com', 80) {|http|
response = http.post('/1.3/?method=lists', data)
}
p response.body
That's the lists() method (for simplicity) and you'd have to build up (and urlencode your values!) your the full POST params rather than simply providing the hash.
Did you take a look at the many gems already available for ruby?
http://apidocs.mailchimp.com/downloads/#ruby
The bigger problem, and main reason I'm replying to this, is that your API Key is not obfuscated nearly well enough. Granted I'm used to working with them, but I was able to guess it very quickly. I would suggest immediately going and disabling that key in your account and then editing the post to actually have completely bogus data rather than anything close to the correct key. The list id on the other hand, doesn't matter at all.
You'll be able to use your hash if you convert it to json before passing it to Net::HTTP. The combined code would look something like:
mailchimp = {}
mailchimp['apikey'] = 'APIKEYAPIKEYAPIKEYAPIKEY'
mailchimp['id'] = '8037342dd1874'
mailchimp['email_address'] = "email#gmail.com"
mailchimp['merge_vars[FNAME]'] = "FirstName"
mailchimp['output'] = 'json'
response = nil
Net::HTTP.start('us2.api.mailchimp.com', 80) {|http|
response = http.post('/1.3/?method=listSubscribe', mailchimp.to_json)
}

Rails Builder::XmlMarkup for Web Service - Repetitive Section

I am using Builder to construct XML messages being sent to a WebService. Each of the different methods require different xml but they all have a set of common elements to start of the request (mostly account authentication stuff). Is there any way to do it in a DRY way? Here is my code for constructing a change pass phrase request:
# XML REQUEST SETUP
msg = Builder::XmlMarkup.new(:indent=>2)
query = {}
test_hsh = self.testmode ? {:Test => "YES"} : {}
# BUILD THE REQUEST
query[:changePassPhraseRequestXML] = msg.ChangePassPhraseRequest(test_hsh) do |asr|
asr.RequesterID APP_CONFIG[:endicia_partner_id].to_s
asr.RequestID "1"
asr.CertifiedIntermediary do |ci|
ci.AccountID APP_CONFIG[:endicia_account_number].to_s
ci.PassPhrase APP_CONFIG[:endicia_passphrase].to_s
end
asr.NewPassPhrase APP_CONFIG[:passphrase].to_s
end
Basically all the elements except the NewPassPhrase one are common to all (or most) requests. Right now I copy the same code over and over but I don't like this at all.
Any ideas on Dry'ing it up?
As soon as I posted this. I had an idea, put the first set into their own method. Duh!
def account_status(options = {})
# XML REQUEST SETUP
msg = Builder::XmlMarkup.new(:indent=>2)
query = {}
test_hsh = self.testmode ? {:Test => "YES"} : {}
# BUILD THE REQUEST
query[:changePassPhraseRequestXML] = msg.ChangePassPhraseRequest(test_hsh) do |asr|
self.add_authentication_elements(asr)
asr.NewPassPhrase APP_CONFIG[:new_pass_phrase].to_s
end
end
def add_authentication_elements(parent_node)
parent_node.RequesterID self.endicia_partner_id.to_s
parent_node.RequestID "1"
parent_node.CertifiedIntermediary do |ci|
ci.AccountID self.endicia_account_number.to_s
ci.PassPhrase self.endicia_passphrase.to_s
end
end
Works great! Another option would of course be to extend Builder in some way but this is nice and simple.

Resources