I know we can sync data using rhodes without Rhosync or Rhoconnect by using direct web service, but I'm here little bit confuse where to place that code for webservice call and how do we initialize it. Can anyone help me with small example?
Thanks in Advance.
I got it and it works for me.
class ProductController < Rho::RhoController
include BrowserHelper
# GET /product
def index
response = Rho::AsyncHttp.get(:url => "example.com/products.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
render :back => '/app'
end
# GET /product/{1}
def show
id =#params['id']
response = Rho::AsyncHttp.get(:url => "example.com/products/"+ id +".json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# GET /product/new
def new
#product = product.new
render :action => :new, :back => url_for(:action => :index)
end
# GET /product/{1}/edit
def edit
id =#params['product_id'].to_s
response = Rho::AsyncHttp.get(:url => "example.com/products/#{id}.json",
:headers => {"Content-Type" => "application/json"})
#result = response["body"]
end
# POST /product/create
def create
name = #params['product']['name']
price = #params['product']['price']
body = '{"product" : {"name" : "'+ name +'","price" :"'+ price +'" } }'
#result = Rho::AsyncHttp.post(:url => "example.com/products.json",
:body => body, :http_command => "POST", :headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/update
def update
name=#params['product']['name']
price=#params['product']['price']
body = '{"product" : {"name" : "' + name + '","price" :"' + price + '" } }'
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:body => body, :http_command => "PUT",:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
# POST /product/{1}/delete
def delete
id = #params["product_id"].to_s
response = Rho::AsyncHttp.post(:url => "example.com/products/#{id}.json",
:http_command => "DELETE",
:headers => {"Content-Type" => "application/json"})
redirect :action => :index
end
end
Most easy form of http server request is next:
Rho::AsyncHttp.get(
:url => "http://www.example.com",
:callback => (url_for :action => :httpget_callback)
)
where httpget_callback is name of the controller callback method.
See more details at official Rhodes docs.
Related
I am using recycled code from a project but in this version I am not having good results.
I use Rails 5.2.2 and RVM Ruby 2.7.1
I need to use this function to call an ajax and deliver the already stored data of a client and fill out a form, the data will be searched through the RUN of each client
I don't understand why the match () are not working for me
Controller Pacientes
class Ajax::PacientesController < ApplicationController
layout nil
def obtener_datos_paciente
#usuario = params[:rut]
usuario = Usuario.first :rut => params[:rut]
puts usuario.inspect.yellow
if usuario.nil?
render :json => {
:exito => true,
:mensaje => "No existen registros asociados al rut #{params[:rut]}."
}
else
render :json => {
:exito => true,
:es_empresa => true,
:mensaje => "El paciente con rut #{params[:rut]} ya existe.",
:data => {
:id => usuario.id,
:rut => usuario.rut,
:primer_nombre => usuario.primer_nombre,
:segundo_nombre => usuario.segundo_nombre,
:apellido_paterno => usuario.apellido_paterno,
:apellido_materno => usuario.apellido_materno,
:direccion => usuario.direccion,
:ciudad => usuario.ciudad,
:comuna => usuario.comuna,
:telefono => usuario.telefono,
:email => usuario.email
}
}
end
rescue Excepciones::DatosNoExistentesError => e
flash.now[:info] = e.message
render :json => { :mensaje => e.message }
end
end
Routes
match(
"ajax/pacientes/:rut" => "ajax::pacientes#obtener_datos_paciente",
:as => :obtener_datos_paciente,
:via => :get
)
Controller Usuario
require 'json'
class UsuariosController < ApplicationController
helper_method :url_paciente
def index
#usuarios = Usuario.all
end
def ingreso_paciente
end
def registrar_ingreso
end
def ingresar_ficha_kinesica
alias url_paciente obtener_datos_paciente_ajax_pacientes_path
end
end
The easiest fix would be to rename your controller to:
class PacientesController < ApplicationController and match to "ajax/pacientes/:rut" => "pacientes#obtener_datos_paciente"
If your controller must exist in the Ajax namespace, then it should probably have a namespaced route as well. An example can be found in this answer.
i successfully got generating tokens working on the ios side, and i have a heroku rails app set up. How do i retrieve this token on the server side?
getting the error `Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method []' for nil:NilClass):
app/controllers/login_controller.rb:11:in 'log_in'
here is my controller code:
class LoginController < ApplicationController
def index
end
def log_in
puts params
headers = {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY"}
query = {:username => params[:user][:username],
:password => params[:user][:password]}
#response = HTTParty.get('https://api.parse.com/1/login',
:query => query,
:headers => headers)
session[:session_token] = #response["sessionToken"]
session[:object_id] = #response["objectId"]
#object_id = session[:object_id]
#test = HTTParty.get("https://api.parse.com/1/classes/_User/#{#object_id}",
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" =>"APIKEY"} )
session[:stripe_acct_id] = #test["uid"]
end
def logout
logout = HTTParty.post('https://api.parse.com/1/logout',
:headers => {"X-Parse-Application-Id" => "APIKEY",
"X-Parse-REST-API-Key" => "APIKEY",
"X-Parse-Session-Token" => session[:session_token]})
reset_session
redirect_to :controller => "login"
end
def deauthorize
#object_id = session[:object_id]
HTTParty.post("https://connect.stripe.com/oauth/deauthorize",
:basic_auth => { :username => ENV['STRIPE_SECRET'] },
:query => { client_id: ENV['STRIPE_CONNECT_CLIENT_ID'],
stripe_user_id: session[:stripe_acct_id]})
end
end
In your controller add:
protect_from_forgery: :null, only: :log_in
For your error, it's because you don't send user object in your post request.
I was working on an app in which I need to work with ipn, but it seems it does not work well.
I am trying to get the notification in success action and have specified the correct url in paypal sandbox.
def success
topup = current_user.topups.last
logger.debug "topup -------->"
logger.debug topup.amount.to_i
# raise request
details = EXPRESS_GATEWAY.details_for(topup.express_token)
logger.debug "details ------->"
logger.debug details.payer_id
# raise params[:payer_id]
response = EXPRESS_GATEWAY.purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:token => topup.express_token,
:payer_id => details.payer_id
})
logger.debug "Response starts here --------->"
logger.debug response
if response.success?
amount = topup.amount.to_i
current_user.credits = current_user.credits.to_i + amount
current_user.save!
flash[:success] = "Thank you for the top up"
# #account_history = current_user.account_histories.build
# #account_history.update_attribute(:type => "Top Up", :details => "", :amount => amount, :user_id => current_user.id)
redirect_to current_user
notify = Paypal::Notification.new request.raw_post
logger.info "Notifying --------->"
logger.info notify
logger.info notify.status
logger.info "Notifying 2 --------->"
logger.info notify.acknowledge
logger.debug notify.status
if notify.acknowledge
logger.debug "Notifying --------->"
logger.debug notify.mc_gross
logger.debug notify.txn_id
end
else
redirect_to root_url
end
end
notify.acknowledge does not return anything (it is blank)
After banging my head for quite some time I was able to solve the issue. Posting my solution just in case anyone is stuck in the similar situation :-
One important thing is that IPN sends post data to the IPN listener so make sure you have a route defined for this.
I also had a before_filter :authenticate_user! , because of which I was getting html code 401. Had to skip before filter for notify action.
def pay_with_account
topup = Topup.find(params[:id])
response = EXPRESS_GATEWAY.setup_purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:currency_code => 'GBP',
:return_url => topups_success_url(topup),
:notify_url => topups_notify_url(topup),
:cancel_return_url => topups_cancel_url(topup),
# :allow_guest_checkout => true,
:items => [{:name => "Topup", :quantity => 1,:description => "Top up my account", :amount => topup.price_in_cents}]
})
topup.update_attribute :express_token, response.token
redirect_to EXPRESS_GATEWAY.redirect_url_for(response.token)
end
This is the return url :-
def success
topup = current_user.topups.last
details = EXPRESS_GATEWAY.details_for(topup.express_token)
response = EXPRESS_GATEWAY.purchase(topup.price_in_cents,{
:ip => request.remote_ip,
:currency_code => 'GBP',
:token => topup.express_token,
:payer_id => details.payer_id
})
if response.success?
amount = topup.amount.to_i
current_user.credits = current_user.credits.to_i + amount
current_user.save!
redirect_to user_payments_path(current_user)
flash[:success] = "Your transaction was successfully completed"
else
flash[:error] = "Your transaction could not be compelted"
redirect_to user_payments_path(current_user)
end
end
This is the notify url :-
def notify
notify = Paypal::Notification.new(request.raw_post)
if notify.acknowledge
#account_history = topup.user.account_histories.build
#account_history.update_attributes(:payment_type => "Top up",:status => notify.status, :amount => notify.gross)
if params[:payer_status] == "verified"
#account_history.update_attributes(:details => "Pay Pal #{#account_history.id}")
elsif params[:payer_status] == "unverified"
#account_history.update_attributes(:details => "Credit Card #{#account_history.id}")
end
#account_history.save
end
render :nothing => true
end
routes :-
get "topups/pay_with_account"
get "topups/pay_without_account"
get "topups/success"
get "topups/cancel"
get "topups/notify"
post "topups/notify
I have a strange problem, i can't even get the source of it.
I'm using ajax GET request to a specified url, that routes to :controller => pages, :action => make_affiche_link, there i have the following:
#album = Album.find( params[:album_id] )
#upd = { :affiche_id => params[:affiche_id] }
if #album.update_attributes( #upd )
#out = {:key => '1', :message => "success"}
render :json, #out.to_json
else
#out = {:key => '0', :message => "something bad is going here..."}
render :json => #out.to_json
end
and what i get is this:
index 49793 out of string
And i have both :affiche_id and :album_id in params properly
Thank you for any help!
It is Json #out = {:key => '1', :message => "success"}, you try convert Json to Json #out.to_json. Use render :json, #out
I am trying to parse XML using rexml Xpath, but facing error as const_missing: XPath in rhomobile application. can anyone give me the solution.
Below is the sample code:
file = File.new(file_name)
begin
require 'rexml/document'
xmldoc = REXML::Document.new(file)
names = XPath.match(xmldoc, "//MP_HOST_NAME" )
in your build.yml file:
extensions:
- rexml
if using blackberry, replace rexml with rhoxml
Assuming you've done this, replace your XPath with:
REXML::XPath.match(xmldoc, "//MP_HOST_NAME" )
Here is a sample controller I knocked to test xml parsing
I can use the get_names method in the view then to get an array of names
require 'rho/rhocontroller'
require 'rexml/document'
class WebServiceTestController < Rho::RhoController
def index
##get_result = ""
Rho::AsyncHttp.get(
:url => 'http://www.somesite.com/some_names.xml',
#:authorization => {:type => :basic, :username => 'user', :password => 'none'},
:callback => (url_for :action => :httpget_callback),
:authentication => {
:type => :basic,
:username => "xxxx",
:password => "xxxx"
},
:callback_param => "" )
render :action => :wait
end
def get_res
##get_result
end
def get_error
##error_params
end
def httpget_callback
if #params["status"] != "ok"
##error_params = #params
WebView.navigate( url_for(:action => :show_error) )
else
##get_result = #params["body"]
begin
# require "rexml/document"
##doc = REXML::Document.new(##get_result)
# puts "doc : #{doc}"
rescue Exception => e
# puts "Error: #{e}"
##get_result = "Error: #{e}"
end
WebView.navigate( url_for(:action => :show_result) )
end
end
def show_error
render :action => :error, :back => '/app'
end
def show_result
render :action => :index, :back => "/app"
end
def get_doc
##doc
end
def get_names
names = []
REXML::XPath.each( get_doc, "//name_or_whatever_you_are_looking_for") do |element|
names << element.text
end
names
end
end
ensure that rhoxml is set in the build.yml file rather than rexml this works fine and it's a little faster