Error using Xpath in Rhomobile - rhomobile

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

Related

ArgumentError: Ajax::Pacientes#obtener_datos_paciente is not a supported controller name

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.

rails controller stream

Hi i have a controller in rails but it gives me an error
ActiveRecord::StatementInvalid in StreamsController#front_page
Mysql2::Error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'EPOCH FROM posts.created_at) - 1327654606)/9000) desc LIMIT 15' at line 1: SELECT `posts`.* FROM `posts` WHERE ((`posts`.`featured` = 1 OR `posts`.`author_id` = 5)) ORDER BY (ln( 1 + posts.likes_count) + (EXTRACT(EPOCH FROM posts.created_at) - 1327654606)/9000) desc LIMIT 15
The StreamsController#front_page are:
def front_page
stream_responder do
#stream = Stream::FrontPage.new(current_user, params[:offset])
#stream_json = PostPresenter.collection_json(#stream.stream_posts, current_user, lite?: true, include_root: false)
end
end
And PostPresenter
require File.join(File.dirname(__FILE__), '..', '..', 'lib', 'template_picker')
class PostPresenter
include ActionView::Helpers::TextHelper
attr_accessor :post, :current_user
def initialize(post, current_user=nil)
#post = post
#current_user = current_user
#person = #current_user.try(:person)
end
def self.collection_json(collection, current_user, opts={})
collection.includes(:author => :profile).map {|post| self.new(post, current_user).as_json(opts)}
end
def as_json(options={})
{
:id => #post.id,
:guid => #post.guid,
:text => #post.raw_message,
:plain_text => #post.plain_text,
:public => #post.public,
:featured => #post.featured,
:created_at => #post.created_at,
:staff_picked_at => #post.staff_picked_at,
:interacted_at => #post.interacted_at,
:tags => #post.tags.as_json,
:tag_list => #post.tags.map(&:name).join(", "),
:post_type => #post.post_type,
:image_url => #post.image_url,
:object_url => #post.object_url,
:favorite => #post.favorite,
:nsfw => #post.nsfw,
:author => PersonPresenter.new(#post.author, current_user),
:o_embed_cache => #post.o_embed_cache.try(:as_api_response, :backbone),
:mentioned_people => [],
:photos => #post.photos.map {|p| p.as_api_response(:backbone)},
:frame_name => #post.frame_name || template_name,
:parent => (options.fetch(:include_root, true) ? parent(options) : nil),
:title => title,
:next_post => next_post_path,
:previous_post => previous_post_path,
:screenshot_url => #post.screenshot_url,
:screenshot_width => #post.screenshot_width,
:screenshot_height => #post.screenshot_height,
:show_screenshot => self.show_screenshot?,
:has_gif => self.has_gif?,
:conversation_id => #post.conversation_id,
:interactions => options.fetch(:lite?, false) ? lite_interactions : heavy_interactions,
:original => #post.original?
}
end
def next_post_path
Rails.application.routes.url_helpers.next_post_path(#post)
end
def previous_post_path
Rails.application.routes.url_helpers.previous_post_path(#post)
end
def heavy_interactions
PostInteractionPresenter.new(#post, current_user).as_json
end
def lite_interactions
PostInteractionPresenter::Lite.new(#post, current_user).as_json
end
def title
#post.text.present? ? truncate(#post.plain_text, :length => 118) : I18n.translate('posts.presenter.title', :name => #post.author.name)
end
def template_name #kill me, lol, I should be client side
#template_name ||= TemplatePicker.new(#post).template_name
end
def parent(opts={})
PostPresenter.new(#post.parent, current_user).as_json({:include_root => false}.merge(opts)) if #post.respond_to?(:parent) && #post.parent.present?
end
def show_screenshot?
#post.screenshot_url.present?
end
def has_gif?
return false unless #post.photos.present?
return 'gif' if #post.photos.detect{ |p| p.url && p.url.match(".gif") }.present?
end
protected
def person
#current_user.person
end
def user_signed_in?
#current_user.present?
end
end
I dont know where am i do wrong..? badly need help on this
You're closing an unopened parenthesis in the query.
'EPOCH FROM posts.created_at) ...'

How to use Rhodes without Rhosync or RhoConnect?

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.

Ruby on Rails - right way to take form input and insert it into the database

I have this form:
= form_for([:mobile,#disclosure], :html => {:id => "disclosure-form", :remote => true}) do |f|
%p
=f.label :display_as, (t :select_disclosure_type)
=f.select :display_as, options_from_collection_for_select(Disclosure.basics, :display_as,
:name, f.object.display_as)
%p
=f.label :notes, (t :notes)
=f.text_area :notes, :class => "#{validation_rules(:free_disclosure_notes)}", :rows => 5 , :id => "disclosure_notes_entry"
= buttonset({:submit_label => (t "buttons.influencers.disclosures.create"),:submit_css_class => "call-to-action",
:cancel_url => "#",:direction => :left_to_right})
and I have this controller so far:
def create
Rails.logger.debug "-"*100
Rails.logger.debug session.inspect
Rails.logger.debug "-"*100
provider = nil
#disclosure = params[:disclosure-form].blank?
resource = build_resource({})
begin
if disclosure.nil?
print "hello 1"
else
print "hello 2"
end
rescue Exception => ex
Rails.logger.debug ex
end
respond_to do |format|
format.html{}
end
end
But I am not sure how to get the #disclosures object to be populated so that I can insert it into the database?
How do I get the right data out of the form and add it to the database?
Thanks!!
Your form data should be in params[:disclosure] hash. So, in your create action you would do something like:
def create
#disclosure = Disclosure.new(params[:disclosure])
if #disclosure.save
# redirect to show or something else
else
# render 'new' for with validation errors
end
end
This should save your object in DB. If there is no validation errors.
I'm not sure what this line does: #disclosure = params[:disclosure-form].blank?

How to get gateway response from model into controller - Ruby on Rails

My application uses activemerchant to process payments. I'm using Eway as my payment gateway. I'm storing credit card details with Eway to keep them out of my application database.
I'm using a method store which returns a response with a customer billing id that I can use at a later time to process the order.
http://rdoc.info/github/Shopify/active_merchant/master/ActiveMerchant/Billing/EwayManagedGateway
My main issue is how do I get the response value into my controller so I can save it to the member model.
I've created a simple ruby file to test this all works and it does. I just need to convert this code to work inside my rails app.
require "rubygems"
gem 'activemerchant', '1.15.0'
require 'activemerchant'
ActiveMerchant::Billing::Base.mode = :production
gateway = ActiveMerchant::Billing::EwayManagedGateway.new(
:login => '12345678',
:username => 'mylogin#example.com',
:password => 'mypassword'
)
credit_card = ActiveMerchant::Billing::CreditCard.new(
:type => "visa",
:number => "4444333322221111",
:verification_value => "123",
:month => "11",
:year => "2011",
:first_name => "John",
:last_name => "Citizen"
)
options = {
:order_id => '1230123',
:ip => "127.0.0.1",
:email => 'john.citizen#example.com',
:billing_address => { :title => "Mr.",
:address1 => '123 Sample Street',
:city => 'Sampleville',
:state => 'NSW',
:country => 'AU',
:zip => '2000'
},
:description => 'purchased items'
}
if credit_card.valid?
response = gateway.store(credit_card, options)
if response.success?
puts "Credit Card Stored. #{response.message}"
customer = response.params['CreateCustomerResult']
puts "Customer Id: #{customer}"
else
puts "Error: #{response.message}"
end
else
puts "Error, credit card is not valid. #{credit_card.errors.full_messages.join('. ')}"
end
Here is the relevant code in my order model.
serialize :params
cattr_accessor :gateway
def response=(response)
self.success = response.success?
self.message = response.message
self.params = response.params
self.billing_id = response.params['CreateCustomerResult']
rescue ActiveMerchant::ActiveMerchantError => e
self.success = false
self.message = e.message
self.params = {}
self.billing_id = nil
end
def store
response = Order.gateway.store(credit_card, options)
end
Here is my order controller create code.
def create
#member = current_member
#order_deal = Deal.find(params[:deal_id])
#order = #order_deal.orders.build(params[:order])
#order.member_id = current_member.id
#order.ip_address = request.remote_ip
#deal = #order_deal
if #order.save
if #order.store
render :action => "success"
flash[:notice] = "Successfully processed your order."
else
render :action => "new"
end
else
render :action => 'new'
end
end
So essentially I want to get the
response.params['CreateCustomerResult']
and add it to my member model under
member.billing_id = response.params['CreateCustomerResult]
How can I do this?

Resources