开发者

Catching XML response using Nokogiri in rails 3.0.9

I am trying to authenticate sign in process, In my sign in process if the user name & password is correct then user will login in to his dashboard but if the username & password is wrong then I am getting one XML response.

Following is the session_controller code

{

require 'net/http'
require 'uri' 
require 'open-uri'
require 'nokogiri'
class SessionsController < ApplicationController
 def new
 @title = "Sign in"

 end

 def create

  redirect_to "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}"

a = "http://<SERVER_IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}"

doc = Nokogiri::XML(open(a).read)  
    doc.css('status').each do |link|


  # Create error message and re-render signin page

 @b = link.content


 end
end

 def destroy
  sign_out
  redirect_to root_path
 end
 end

}

I am getting this kind of XML response from server

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
<name>login</name>
<status>failed</status>
<status_mes开发者_如何学Csage>Error description</status_message>
</action>

ones I get this response I want to flash the error message using the above XML response.

If any one has any idea will save my day.


Hey Folks I have finally done with the above functionality.That is not much tough as I thought for other users I am pasting the exact snippet here

def create

 a = "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}"   

 # Nokogiri Gem is used to Catch the XML response from the MOR & call the appropriate action on the received status

  doc = Nokogiri::XML(open(a))
     doc.xpath('/action/status').each do |link|  
    @abc = link.content
     end 

    # Condition to check whether the received response is 'Ok' or 'Failed' 

    if @abc == 'failed'

            flash[:notice] = "Invalid Username/Password" # If condition is failed redirect to root page
             redirect_to '/' 
           else
                # if condition is 'ok' redirect to MOR user dashboard

               redirect_to "http://<SERVER IP>/billing/api/login?u=#{params[:session][:email]}&p=#{params[:session][:password]}"
         end                                        

end


Nokogiri gives you direct access to the text of the document:

require 'nokogiri'

doc = Nokogiri::XML(
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<action>
<name>login</name>
<status>failed</status>
<status_message>Error description</status_message>
</action>'
)

In irb you'd see:

doc.text

>> "\nlogin\nfailed\nError description\n"

You can simplify your code to something like:

doc = Nokogiri::XML(open(a))

if doc.text['failed']
  ...
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜