I have controller's POST action method :
def appinfo
puts session[:arr]
u = User.find_by(apikey: appliance_params[:apikey], id: appliance_params[:id])
if u
render json: session[:arr]
#session[:arr] = nil
puts session[:arr]
else
render json: "UserError : error, i haven't found such user with this params :("
end
end
but also a wrote this code
skip_before_filter :verify_authenticity_token, :only => [:appinfo]
I send POST request to .../appinfo.
And if i want to puts session[:arr] in my method appinfo, it is give me nothing
How can i get session[:arr] ?:
Related
I have made this code in ApplicationController. This is a method which runs at the start of any method to run. I want to test this method with rspec and want to know that the gender is giving right output or wrong.
this is the route of the code
get ':sex/names/:name_kanji', to: 'names#show'
And this is the application controller:
class ApplicationController < ActionController::Base
before_action :check_sex
private
def check_sex
#header_color = nil
#header_nav_hash = {'other' => nil, 'boy' => nil, 'girl' => nil}
#page_scoop = params[:sex].presence || 'other'
unless #page_scoop.match(/^(boy|girl|other)$/)
render_404
end
if #page_scoop == "boy" || #page_scoop == "girl"
#gender_base = #page_scoop
end
#header_nav_hash[#page_scoop] = 'is-active'
#header_color = #page_scoop == 'boy' ? 'is-info' : 'is-danger' if #page_scoop != 'other'
end
def render_404
render template: 'errors/error_404' , status: 404 , layout: 'application' , content_type: 'text/html'
end
def render_500
render template: 'errors/error_500' , status: 500 , layout: 'application' , content_type: 'text/html'
end
end
I would inspect the instance variables that being set in the before_action. It would look something like this:
describe 'on GET to :show' do
before do
get :show, params: { <valid params here> }
end
it 'sets #page_scoop' do
expect(assigns(:page_scoop)).to eq 'boy'
end
end
I am using Zapier to search some information in google sheets. I used Webhocks to send a GET to his server with a JSON information. The response of GET is an "OK" and I can't custom this.
So, they will execute a task, find what a I want and return a value, but the response must be a GET in my server, and I don't know how to intercept this response in my route.
I'm trying to study Rails Rack to intercept de request in my app, but I don't know how to send the response to the event that sent the first GET.
How is my middleware:
class DeltaLogger
def initialize app
#app = app
end
def call env
Rails.logger.debug "#{env['QUERY_STRING']}"
#status, #headers, #response = #app.call(env)
[#status, #headers, #response]
end
end
Thanks!
Example
So, to get the value returned from Zapier, I created two routes and a global class cache.
class Zapier
require 'httparty'
def initialize
#answer = ""
#id = 0
end
def request(uri, task)
last_event = Event.last
puts last_event.inspect
if last_event.nil?
last_id = 0
else
last_id = last_event.event_id
end
event_id = last_id + 1
Event.find_or_create_by(event_id: event_id)
result = HTTParty.post(uri.to_str,
:body => {id: event_id, task: task}.to_json,
:headers => {'content-Type' => 'application/json'})
#answer = ""
#id = event_id
end
def response(event_id, value)
if event_id != #id
#answer = ""
else
#answer = value
end
end
def get_answer
#answer
end
end
And my controller:
class ZapierEventsController < ApplicationController
require 'zapier_class'
before_action :get_task, only: [:get]
before_action :get_response, only: [:set]
##zapier ||= Zapier.new
def get
##zapier.request('https://hooks.zapier.com',#task)
sleep 10 #Wait for response
#value = ##zapier.get_answer
render json: { 'value': #value }, status:
end
def set
##zapier.response(#id, #value)
render json: { 'status': 'ok' }, status: 200
end
def get_task
#task = params["task"]
end
def get_response
#id = Integer(params["id"])
#value = params["value"]
end
end
Now i have to make a Task Mananger
I have implemented my own object creation logic by overriding the create action in a JSONAPI::ResourceController controller.
After successful creation, I want to render the created object representation.
How to render this automatically generated JSON API response, using the jsonapi-resources gem?
Calling the super method does also trigger the default resource creation logic, so this does not work out for me.
class Api::V1::TransactionsController < JSONAPI::ResourceController
def create
#transaction = Transaction.create_from_api_request(request.headers, params)
# render automatic generated JSON API response (object representation)
end
end
You could do something like this:
class UsersController < JSONAPI::ResourceController
def create
user = create_user_from(request_params)
render json: serialize_user(user)
end
def serialize_user(user)
JSONAPI::ResourceSerializer
.new(UserResource)
.serialize_to_hash(UserResource.new(user, nil))
end
end
this way you will get a json response that is compliant with Jsonapi standards
render json: JSON.pretty_generate( JSON.parse #transaction )
def render_json
result =
begin
block_given? ? { success: true, data: yield } : { success: true }
rescue => e
json_error_response(e)
end
render json: result.to_json
end
def json_error_response(e)
Rails.logger.error(e.message)
response = { success: false, errors: e.message }
render json: response.to_json
end
render_json { values }
I have the following controller:
class Api::V1::FeedbacksController < ApplicationController
before_action :authenticate_user!
def create
#feedback = current_user.feedbacks.create(
feedback_type: params[:selectedType],
message: params[:message]
)
json_response(#feedback)
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
end
Feedback.rb
validates :message, presence: true, length: { in: 1..1000 }
This works great when message is between 1 to 1000 in length. If the controller is submitted more than 1000 characters, the controller is still respond back but without the error.
What is the right way in Rails 5 to have the controller return an error if the create method above fails?
The usual rails way is to test the return value of .save:
def create
#feedback = current_user.feedbacks.new(
feedback_type: params[:selectedType],
message: params[:message]
)
if #feedback.save
json_response(#feedback)
else
json_response(#feedback.errors, :some_other_status)
# you could also send #feedback directly and then in your JSON response handler
# to test if the json contains values in the object.errors array
end
end
private
def json_response(object, status = :ok)
render json: object, status: status
end
You can use this doc to find the right statuts code to return https://cloud.google.com/storage/docs/json_api/v1/status-codes
def purchase
...
perform_payment_post
redirect_to :action => 'billing'
...
end
def perform_payment_post
params[:coverages] ||= {}
params[:customer][:coverage_addon] = (params[:coverages].collect { |k,v| k }).join(', ')
params[:customer][:coverage_ends_at] = 1.year.from_now
Rails.logger.info("--- id = #{cookies.signed[:incomplete_gaq_customer_id]}")
id = cookies.signed[:incomplete_gaq_customer_id]
return redirect_to :action => #is_affiliate_user ? 'affiliate':'quote' if id.nil?
#customer = Customer.find(cookies.signed[:incomplete_gaq_customer_id])
return redirect_to :action => 'please_call' if #customer.status_id != 0
#customer.update_attributes(params[:customer])
#customer.notes.create({ :notes_text => #note }) if #note
if params[:property_id].to_i == 0 then #customer.properties.create(params[:property]) end
end
Getting Error on purchase method on line redirect_to :action => "billing".
AbstractController::DoubleRenderError: Render and/or redirect were called multiple times in this action. Please note that you may only call render OR redirect, and at most once per action. Also note that neither redirect nor render terminate execution of the action, so if you want to exit an action after redirecting, you need to do something like "redirect_to(...) and return".
Please Help Me.
If you want to return early in controller you either need to write it like this
redirect_to(:action => #is_affiliate_user ? 'affiliate':'quote') and return if id.nil?