redirect_to external url passing params - ruby-on-rails-3

I need to pass params in a redirect_to method to an external url...
I know that I can do something like this with a redirect:
redirect_to my_url_path(param1: "foo", param2: "bar")
But I want to do this with an external url. For example:
redirect_to "www.example.externaldomain.com/process/XIGHTDJTRIDEOR", param1: "foo", param2: "bar"

You can use the ruby URI module and create your own helper:
def generate_url(url, params = {})
uri = URI(url)
uri.query = params.to_query
uri.to_s
end
Then just get the url:
redirect_to generate_url("www.example.externaldomain.com/process/XIGHTDJTRIDEOR", :param1 => "foo", :param2 => "bar")

Related

Rspec;How to include params inside the body

Rspec spec fails on the following test case. Can anyone please help me with sending params inside the body?
Test case:
describe 'POST search' do
it 'renders search' do
request.headers['Content-Type'] = 'application/json'
request.headers['Accept'] = 'application/json'
post :search, body: {name: {query_type: 'match', value: ['xy']} }.to_json
expect(response.status).to eq(200)
expect(response.body.include?('TWEEDLE'))
end
end
Controller:
def search
page_params = pagination_params
query_hash = QueryPreprocessor.params_to_query_with_types(JSON.parse(request.body.read).deep_symbolize_keys)
logger.info "query_hash: #{query_hash}"
es_query_json = Elastic::QueryBuilder.facility_search_v1(query_hash, page_params).to_json
logger.info "es query: #{es_query_json}"
facilities = facility_helper.search es_query_json
json_response build_facilities_response(facilities)
rescue ApiError => e
render json: e.response, status: e.status
end
and these are the params which I want to include inside the body, which is being called in the controller:
def pagination_params
page_params = {}
page_params['size_params'] = params[:size] || 50
page_params['from_params'] = params[:from] || 0
page_params['sort_params'] = params[:sort]
page_params['order_params'] = params[:order]
page_params
end
Rspec should passes, with pagination params included inside the body.
You can POST json with "as: :json".
describe 'POST search' do
it 'renders search' do
request.headers['Content-Type'] = 'application/json'
request.headers['Accept'] = 'application/json'
post :search, params: {name: {query_type: 'match', value: ['xy']} }, as: :json
expect(response.status).to eq(200)
expect(response.body.include?('TWEEDLE'))
end
end

rspec controller spec for js request

In my controller specs everything works fine (update action, edit action, etc. also via js request), except the create action. For some reason it doesn't change the Task.count, but the http response is 200.
There are no other callbacks and in dev ENV it saves the task in the db. This factory passes in model spec. I also tried to comment out the Notification.create, TaskCreatorJob and Conversation.create.., but didn't help. In my other controller specs the expect { create_action }.to change{Class.count}.by(1) works properly.
What did I miss?
conroller
def create
#task = Task.new(task_params)
#task.assigner_id = current_user.id
if #task.save
Notification.create(recipient_id: #task.executor_id, sender_id: current_user.id, notifiable: #task, action: "assigned")
TaskCreatorJob.perform_later(#task, #task.executor, #task.assigner)
Conversation.create_or_find_conversation(#task.assigner_id, #task.executor_id)
respond_to do |format|
format.js
end
else
respond_to do |format|
format.js
end
end
end
factory
factory :task do
content { Faker::Lorem.sentence }
deadline { Faker::Time.between(DateTime.now + 2, DateTime.now + 3) }
association :executor, factory: :user
association :assigner, factory: :user
end
tasks_controller_spec.rb
.....
before(:each) do
login_user
end
describe "POST create" do
context "with valid attributes" do
let!(:user) { create(:user) }
let!(:profile) { create(:profile, user: #user) }
let!(:profile_2) { create(:profile, user: user) }
let!(:conversation) { create(:conversation, sender: #user, recipient: user) }
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner: #user, executor: user) }
it "saves the new task in the db" do
expect{ create_action }.to change{ Task.count }.by(1)
end
it "responds with success" do
create_action
expect(response).to have_http_status(200)
end
end
end
It seems in controller spec it's not enough to define task params like assigner: #user, so I had to change
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner: #user, executor: user) }
to
subject(:create_action) { xhr :post, :create, user_id: #user.id, task: attributes_for(:task, assigner_id: #user.id, executor_id: user.id) }

How to call helper method through select_tag

I am trying to call helper method from select_tag. I tried this:
<%= select_tag(:themes, options_for_select({"Black" => "compiled/styles", "Green" => "compiled/styles2"})) %>
When I put alert(this.options[this.selectedIndex].value) instead of calling method, it works. How can I change my code to call the method as desired?
EDIT
I have this on my application.js
$(document).ready(function() {
$('#display_themes').change(function(){
$.ajax({url: '<%= url_for :controller => 'application', :action => 'set_themes()', :id => 'this.value' %>',
data: 'selected=' + this.value,
dataType: 'script'
})
})
});
And in controller I have set_themes methode
def set_themes()
#themes = params[:id]
respond_to do |format|
redirect_to '/galleries'
format.html # index.html.erb
format.xml { render :xml => #themes }
end
end
The problem now is #themes still empty even I change the dropdown
Routes.rb
match '', :controller => 'application', :action => 'set_themes()'
To route to application#set_themes:
match '/set_themes', to: 'application#set_themes', as: :set_themes
With that done, just direct the url in ajax as follows:
$.ajax({url: "<%= set_themes_path %>",
It should be #themes = params[:selected] in your controller based on what you are trying to do in application.js.

Passing argument to decorator from controller in Rails using Draper

I couldn't figure out how to pass an argument to a decorator from a controller:
The decorator:
def as_json(options = nil)
{
:name => user.name,
:dob => user.dob
:created_at => user.created_at,
:url => user
}
end
The controller:
format.json { render :json => UserJsonDecorator.new(#user)}
Just passing an extra argument to the new method does not work:
UserJsonDecorator.new(#user,options)
Any ideas?
I was basically using it wrong.
correct form to pass additional arguments is:
UserJsonDecorator.new(#user).to_json(options)

BancBox REST API POST createClient

I've spent the last day trying to get this to work in my Rails app, but continually get the response:
{"code"=>"E-C-343", "message"=>"Unrecognized JSON Request."}
BancBox's Documentation is pretty light, so I'm at a bit of an impasse on how to solve this.
Does anyone have an example of a successful API call to createClient at BancBox utilizing REST?
My Post API call utilizing HTTParty:
include HTTParty
format :json
def save_with_bancbox(params = {})
post_params = { :authentication => { :apiKey => BANCBOX_KEY,
:secret => BANCBOX_SECRET
},
:subscriberId => BANCBOX_ID,
:firstName => params[:first_name],
:lastName => params[:last_name],
:ssn => params[:ssn],
:dob => params[:dob],
:address => { :line1 => params[:address_line_1],
:line2 => params[:address_line_2],
:city => params[:city],
:state => params[:state],
:zipcode => params[:zipcode]
},
:homePhone => params[:dob],
:email => params[:email]
}
response = HTTParty.post( BANCBOX_REST_URL,
:body => post_params)
logger.debug "Response -- #{response}"
save!
end
Please try the below code after changing apikey, secret and subscriberid
require "net/https"
require 'rubygems'
require 'json'
require 'httparty'
###########################bancbox.rb in config/initializers#################
BANCBOX_API_KEY = "__KEY__"
BANCBOX_API_SECRET = "__SECRET__"
BANCBOX_SUBSCRIBER_ID = "__SUB_ID__"
BANCBOX_API_URL = "https://sandbox-api.bancbox.com/BBXPortRest"
module Bancbox
class API
include HTTParty
debug_output $stdout
base_uri "#{BANCBOX_API_URL}"
def initialize(u=BANCBOX_API_KEY,p=BANCBOX_API_SECRET)
auth = {:apiKey => u, :secret => p}
#options = {:body => {:authentication =>auth,:subscriberId=>BANCBOX_SUBSCRIBER_ID}, :headers => { 'Content-Type' => 'application/json', 'Accept' => 'application/json' }}
end
#USERS
def create_client(options={})
options = options.merge(#options[:body])
#options.merge!({:body => options.to_json})
response = self.class.post("/createClient",#options)
#required_fields- subscriberId,firstName,lastName,ssn,dob,address,homePhone,email
end
def get_schedules(options={})
#options.merge!({:query => {:subscriberId => BANCBOX_SUBSCRIBER_ID}})
#options.merge!({:query => options})
self.class.post("/getSchedules",#options)
end
end
end
b = Bancbox::API .new
b.create_client({:firstName=> "Bipen",:lastName=> "Sasi",:ssn=>"334-444-4444",:dob=> Date.parse("January 1st 1988"), :address=>{:line1=> "4408 walnut st", :line2=>"apt 3r",:city=> "philly",:state=>"pa",:zipcode=>"19110"}, :homePhone=> "2672551161",:email=>"bipen#lokalty.com"})
I think you should POST the request to
https://sandbox-api.bancbox.com/BBXPortRest/createClient
instead of
https://sandbox-api.bancbox.com/BBXPortRest/
Also make sure to set the content type as application/json
In general, you post your request to https://sandbox-api.bancbox.com/BBXPortRest/<method>