I have a this class middleware:
class RedirectIt
require "net/https"
require "uri"
require 'open-uri'
APP_DOMAIN = 'http://www.mydomain.com'
def initialize(app)
#app = app
end
def call(env)
request = Rack::Request.new(env)
response = Rack::Response.new(env)
response.headers['Cache-Control'] = "public, max-age=#{84.hours.to_i}"
response.headers['Content-Type'] = 'image/png'
response.headers['Content-Disposition'] = 'inline'
response.body = "#{open('http://s3-eu-west-1.amazonaws.com/bucket/asdas.png').read}"
end
end
The problem is just that it gives the error:
Started GET "/?view=boks" for 127.0.0.1 at 2012-04-01 04:07:58 +0200
NoMethodError (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]=):
Are am doing something wrong? I have tried to rewrite this code I had in the controller:
def image_proxy
image_url = "http://s3-eu-west-1.amazonaws.com/bucket#{request.path}"
response.headers['Cache-Control'] = "public, max-age=#{84.hours.to_i}"
response.headers['Content-Type'] = 'image/png'
response.headers['Content-Disposition'] = 'inline'
render :text => open(image_url, "rb").read
end
The solution.
#PROXY BILLEDER
status, headers, response = #app.call(env)
headers['Cache-Control'] = "public, max-age=#{84.hours.to_i}"
headers['Content-Type'] = 'image/png'
headers['Content-Disposition'] = 'inline'
response_body = "#{(open('http://s3-eu-west-1.amazonaws.com/mybucket#{request.path()}')).read}"
[status, headers, response_body]
Related
I'm on an mission create an XML file and then POST this file to a server address. However I cant crack why it wont send, im currently stuck getting a "TypeError in CatalogController#gen_xml" > "String can't be coerced into Integer".
However im quite new to this and dont fully grasp to how to best execute this. Any help would be greatly appreciated!
Controller
class CatalogController < ApplicationController
require "builder/xmlmarkup"
require 'builder'
require 'rubygems'
require 'net/http'
def gen_xml
#xml = Builder::XmlMarkup.new
#catalogs=Catalog.all
url = "https://xxx.xxxx.com/xxxCXMLxx.aw/xx/cxml";
request = Net::HTTP::Post.new(url)
#request.add_field "Content-Type", "application/xml"
request.body = #xml
url = URI.parse(url)
req = Net::HTTP::Post.new(url.request_uri)
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = (url.scheme == "https")
#response = http.request(req)
response = http.post(url, #xml, initheader = {'Content-Type' =>'text/xml'})
end
end
View with Button to call method
Super cXML Generator!
<%= form_tag catalog_gen_xml_path, method: :post do %>
<%= submit_tag 'Call Action' %>
<% end %>
Routes File
Rails.application.routes.draw do
get 'catalog/gen_xml'
post 'catalog/gen_xml'
end
Error Trace
Extracted source (around line #24):
22 http.use_ssl = (url.scheme == "https")
23 #response = http.request(req)
24 response = http.post(url, #xml, initheader = {'Content-Type' =>'text/xml'})
25 end
26 end
27
app/controllers/catalog_controller.rb:24:in `gen_xml'
Rails.root: /Users/i303072/railsapps/xmlbuilder
XML Builder File - gen_xml.builder
#xml.instruct! :xml, :version=>"1.0", :encoding=>"UTF-8"
#xml_markup.declare! :DOCTYPE, :chapter, :SYSTEM, "../dtds/chapter.dtd"
xml.cXML(:payloadID=>"XX", :timestamp=>"2018-03-11T11:28:01-07:00", :version=>"1.2.029", :xmllang=>"en-US") {
xml.Header {
xml.From {
xml.Credential(:domain=>"ID") {
xml.Identity "AN-T"
}#Credential
}#From
xml.To {
xml.Credential(:domain=>"ID") {
xml.Identity "AV-T"
}#Credential
xml.Correspondent{
xml.Contact(:role=>"correspondent") {
xml.Name("MRO", "xml:lang" => "en")
xml.PostalAddress{
xml.Country("US", "isoCountryCode" => "US")
}#PostalAddress
}#Contact
}#Correspondent
}#To
xml.Sender {
xml.Credential(:domain=>"NetworkID") {
xml.Identity "AN-T"
xml.SharedSecret "xxx"
}#Credential
xml.UserAgent "xxx"
}#Sender
} #Header
xml.Message(:deploymentMode=>"test") {
xml.ProductActivityMessage(:subcontractingIndicator=>"yes") {
xml.ProductActivityHeader(creationDate: "2018-03-13T22:00:00-08:00", messageID: "Cxxx")
}#ProductivityActivityMessage
}#Message
}#cXML
I'm trying to do a request in httparty but it's not working
require 'httparty'
module PvWatch
class Client
include HTTParty
# base_uri ENV["pv_watch_endpoint"]
def login
response = self.class.post('http://pvwatch.xxx.xxx.xxx.net/api/v1/login', options)
end
def options
{
headers: {
'content-type' => 'application/json',
'access-key' => 'FORGET ABOUT THIS',
'authorization' => 'uri=api/v1/login'
},
body: {
username: "case",
password: "123"
}
}
end
end
end
the weird thing is that when i do the request with net/http is working and i don't know what i'm doing wrong with httparty
require 'uri'
require 'net/http'
module PvWatch
class Client
def login
url = URI("http://pvwatch.xxx.xxx.xxx.net/api/v1/login")
http = Net::HTTP.new(url.host, url.port)
request = Net::HTTP::Post.new(url)
request["content-type"] = 'application/x-www-form-urlencoded'
request["access-key"] = 'FORGET ABOUT THIS'
request["authorization"] = 'uri=api/v1/login'
request.body = "username=case&password=123"
response = http.request(request)
puts response.read_body
end
end
end
any idea what i'm doing wrong?
I am doing a http request to a website and I would like to store the value of a div from the response.
This is what I am doing in the controller:
class RoomsController < ApplicationController
require "uri"
require "net/http"
require 'json'
require 'cgi'
def test
dialect = params[:dialect]
text = params[:text]
uri = URI('http://www.degraeve.com/cgi-bin/babel.cgi')
params = { :w => text, :d => dialect }
uri.query = URI.encode_www_form(params)
res = Net::HTTP.get_response(uri)
data = res if res.is_a?(Net::HTTPSuccess)
render json: data.body
end
end
I am passing 2 parameters using GET method to get the response. But I need just the content of a div. How do I do that?
I did this:
dialect = current_user.dialect.name
text = params[:text]
uri = URI('http://www.degraeve.com/cgi-bin/babel.cgi')
params = { :w => text, :d => dialect }
uri.query = URI.encode_www_form(params)
response = Net::HTTP.get_response(uri)
render inline: response.body.html_safe, layout: false if response.is_a?(Net::HTTPSuccess)
and then got the div that I wanted in a .js file.
I have this middleware which is the first:
class RedirectIt
require "net/https"
require "uri"
require 'open-uri'
APP_DOMAIN = 'http://www.konkurrencerher.dk'
def initialize(app)
#app = app
end
#
def call(env)
request = Rack::Request.new(env)
if request.env['HTTP_HOST'] != APP_DOMAIN
#REDIRECT TIL WWW
[301, { "Location" => "#{APP_DOMAIN}#{request.fullpath()}"}, ["Redirecting..."]]
elsif "#{request.fullpath()}".split(".").last == "png"
#PROXY BILLEDER
status, headers, response = #app.call(env)
headers['Cache-Control'] = "public, max-age=#{84.hours.to_i}"
headers['Content-Type'] = 'image/png'
headers['Content-Disposition'] = 'inline'
response_body = "#{(open('http://s3-eu-west-1.amazonaws.com/konkurrencerher#{request.path()}')).read}"
[status, headers, response_body]
else
#app.call(env)
end
end
end
My Heroku log: http://pastie.org/private/wfhvsr2lqfmq9zknenx7q
The HTTP_HOST is just the bare hostname, without the protocol (i.e. www.konkurrencerher.dk), so will never be equal to your APP_DOMAIN constant and you'll always redirect.
Class UserController
def export_users
users = User.all
stream_csv do |csv|
csv << ["Name","Email","Gender"]
users.each do |i|
csv << [i.name,i.email,i.gender]
end
end
end
def stream_csv
require 'fastercsv'
filename = params[:action] + ".csv"
#this is required if you want this to work with IE
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
controller.response.headers["Content-Transfer-Encoding"] = "binary"
end
render :text => Proc.new { |response, output|
csv = FasterCSV.new(output, :row_sep => "\r\n")
yield csv
}
end
end
Err: "#Proc:0x9382539#/sites/app/controllers/export_controller.rb:56"
Using Ruby 1.8 and Rails 3.0.9
So I think the problem here is that I'm not using "Proc" right. Or it's not supposed to act like just another block...
I thought about programming a new logic into the class so that reads better. But if somebody could explain to me why my code is wrong or at least point me in a new direction than I might be able to learn something new here. Thanks
Note: Found a better way:
def export_inverts
require 'fastercsv'
inverts = Invert.all
filename = params[:action] + ".csv"
#this is required if you want this to work with IE
if request.env['HTTP_USER_AGENT'] =~ /msie/i
headers['Pragma'] = 'public'
headers["Content-type"] = "text/plain"
headers['Cache-Control'] = 'no-cache, must-revalidate, post-check=0, pre-check=0'
headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
headers['Expires'] = "0"
else
headers["Content-Type"] ||= 'text/csv'
headers["Content-Disposition"] = "attachment; filename=\"#{filename}\""
headers["Content-Transfer-Encoding"] = "binary"
end
csv_string = FasterCSV.generate do |csv|
csv << ["Genus","Species","Common Name","Pet Name","Gender"]
inverts.each do |i|
csv << [i.scientific_name,i.scientific_name,i.common_name,i.pet_name,i.gender]
end
end
render :text => csv_string
end
Yield can only be used inside a function or a block. Yield is used in a function that takes a block to say, yield some value into the block. Actually it says yield this value into the proc that the block has been converted into with the ampersand operator (in most cases). However, you could pass a Proc to a function that was expecting it.
Here, you just want to return the value from the proc and "yield" isn't needed.