Rails logging from controller upload method - ruby-on-rails

I am very new to Rails, and I can't understand how can I log something from a particular controller method. I implemented a simple file upload, with fileutils:
def file_upload
require 'fileutils'
require 'rest_client'
tmp = params[:file_upload][:my_file].tempfile
logger.info 'log information with logger'
puts 'log information with puts'
p 'log information with p'
file = File.join("public", params[:file_upload][:my_file].original_filename)
FileUtils.cp tmp.path, file
RestClient.post 'http://externalapi', :destination => 'address', :subject => 'subject', :file => file, :api_key => 'apikey'
end
but from within this method the logging doesn't works. However it does within any other method. I am using Ruby 1.9.3 and Rails 4

Related

Why ldap bind is failing on server?

I'm authenticating against LDAP server in my rails application,
the code below is working locally but not on the server.
On the server it throws Net::LDAP::BindingInformationInvalidError (Invalid binding information) when trying to login in the app but works through the console
I'm pretty new to Ruby and can't figure out the proper way to debug it... I know the LDAP configuration is right because i can authenticate and bind from the console or on my local development environment.. I tried to pass :verbose => true to the LDAP constructor but without effect...
require 'net/ldap'
require 'devise/strategies/authenticatable'
module Devise
module Strategies
class LdapAuthenticatable < Authenticatable
def authenticate!
if params[:user]
ldap = Net::LDAP.new :host => 'XX.XX.XX.XX',
:port => 636,
:connect_timeout => 5,
:base => 'CN=Configuration,DC=internal,DC=XX,DC=XX',
:encryption => {
:method => :simple_tls
},
:auth => {
:method => :simple,
:username => ENV['LDAP_USER'],
:password => ENV['LDAP_PASSWORD']
}
result = ldap.bind_as(:base => "OU=Users,OU=XX,DC=XX,DC=XX,DC=XX",
:filter => "(userPrincipalName=#{email})",
:password => password,
)
if result
user = User.find_by(email: email)
success!(user)
else
return fail(:invalid_login)
end
end
end
def email
params[:user][:email]
end
def password
params[:user][:password]
end
end
end
end
Warden::Strategies.add(:ldap_authenticatable, Devise::Strategies::LdapAuthenticatable)
SOLVED
turned out it was the ENV variables that were not read.
Maybe that account is not authorized? Sounds like the problem is in the binding configuration: base => "OU=Users,OU=XX,DC=XX,DC=XX,DC=XX"
More information from other users who encountered this error:
https://gitlab.com/gitlab-org/gitlab-ce/issues/21937
LDAP groups authentication fails: Invalid Binding Information

How to send multiple ".Zip" files in ruby on rails

I am new to Ruby on Rails .I am working on project where I need to send multiple Zip files To client.
I am using RubyZip for this .
def Download
unless params[:fileLists].nil?
file_name = "Peep-#{Time.now.to_formatted_s(:number)}.zip"
t = Tempfile.new("my-temp-filename-#{Time.now.to_formatted_s(:number)}")
Zip::OutputStream.open(t.path) do |z|
for _file in params[:fileLists]
unless _file.empty?
if File.file? _file
#z.add(File.basename(_file),_file)
z.put_next_entry(File.basename _file)
z.print IO.read(_file)
#send_file _file , disposition: 'attachment',status: '200'
end
end
end
end
#Sending Zip file
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
t.close
end
end
end
This is Working fine for all other file formats except Zip files .How it can be done ?
I resolved it by modifying my method .I used IO.binread(_file) instead of IO.read(_file) to read file.
Zip::OutputStream.open(t.path) do |z|
for _file in params[:fileLists]
unless _file.empty?
if File.file? _file
#z.add(File.basename(_file),_file)
z.put_next_entry(File.basename _file)
z.print IO.binread(_file)
end
end
end
end
#Sending Zip file
send_file t.path, :type => 'application/zip',
:disposition => 'attachment',
:filename => file_name
rubyzip is a lib for creating / working with zip archives in ruby.
ยป gem install rubyzip
Sample code
require 'zip/zip'
require 'zip/zipfilesystem'
def download_all
attachments = Upload.find(:all, :conditions => ["source_id = ?", params[:id]])
zip_file_path = "#{RAILS_ROOT}/uploads/download_all.zip"
# see if the file exists already, and if it does, delete it.
if File.file?(zip_file_path)
File.delete(zip_file_path)
end
# open or create the zip file
Zip::ZipFile.open(zip_file_path, Zip::ZipFile::CREATE) { |zipfile|
attachments.each do |attachment|
#document_file_name shd contain filename with extension(.jpg, .csv etc) and url is the path of the document.
zipfile.add( attachment.document_file_name, attachment.document.url)
end
}
#send the file as an attachment to the user.
send_file zip_file_path, :type => 'application/zip', :disposition => 'attachment', :filename => "download_all.zip"
end

Ruby script not running when Process.daemon is added

I have the following simple script, which checks an email account and if there is new mail it forwards the email and sends an SMS. This happens as expected when the script is run without Process.daemon. When it is added, and email is received at the email account, nothing happens (nothing is forwarded and no SMS is sent) and there are no error messages in the console. Any suggestions?
#!/usr/bin/env ruby
require "bundler/setup"
require "mailman"
require "twilio-ruby"
Mailman.config.pop3 = {
:username => 'address#gmail.com',
:password => 'password',
:server => 'pop.gmail.com',
:port => 995,
:ssl => true
}
Mailman.config.poll_interval = 60
Mailman::Application.run do
default do
begin
Ticket.receive_mail(message)
MailForwarder.forwarded_email(message).deliver
#account_sid = 'xxxxxxxxxxx'
#auth_token = 'xxxxxxxxxx'
#client = Twilio::REST::Client.new(#account_sid, #auth_token)
#account = #client.account
#sms = #account.sms.messages.create(
:from => '+1111111111',
:to => '+122222222',
:body => message.subject
)
puts #sms
puts "#{message.subject}"
rescue Exception => e
Mailman.logger.error "Exception occurred whle receiving message:\n#{message}"
Mailman.logger.error [e, *e.backtrace].join("\n")
end
end
Process.daemon
end
I believe you need to set up your script as a daemon before you start up the mailman application. I did a bit of testing, and it worked fine if I called Process.daemon before calling the Mailman::Application.run but it didn't work if I put it where you had it.
So I had it as:
....
Mailman.config.poll_interval = 15
Process.daemon
Mailman::Application.run do
default do
end
end

Rails request spec is not making put request

I decided to write some request specs, in addition to my cucumber scenarios. But failed on my first example:
So there is this put method in my goalsController:
def achieve
#goal.update_attribute(:achieved, true)
redirect_to :back
end
And this is example:
# -*- coding: utf-8 -*-
require 'spec_helper'
describe "Achievements" do
before(:all) do
#bob = Factory(:user, :email => "bob#mail.com", :password => "qweqwe", :password_confirmation => "qweqwe", :money => 500)
#achieve = Factory(:goal, :user => #bob, :title => "Notebook", :price => 100, :achieved => false)
login_user('bob#mail.com', 'qweqwe')
end
it 'can not be achieved twice' do
visit dashboard_path
put achieve_user_goal_path(#bob, #achieve) #Passes it well
#achieve.reload #same with or without this line
#achieve.achieved.should equal true #Fails
end
end
So after put request 'achieved' field becomes true. It works perfectly in my app, and in cucumber step, but not in this rspec example. It's like rspec just ignores line with 'put'.
If I understand how this works correctly, RSpec uses the Test::Unit helpers from Rails. If reads the controller name from what you are describing, so you would need to describe AchievementsController, and not just some string. You don't visit a page then send put, you just describe the controller and send put.
That said, when you are using the capybara integration testing helpers, the unit test helpers like put and get probably don't do what you want, as they will be executed outside of the context of the browser driver. You should instruct Capybara to click the required link or button (or perform whatever action the user performs).

test a file upload using rspec - rails

I want to test a file upload in rails, but am not sure how to do this.
Here is the controller code:
def uploadLicense
#Create the license object
#license = License.create(params[:license])
#Get Session ID
sessid = session[:session_id]
puts "\n\nSession_id:\n#{sessid}\n"
#Generate a random string
chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
newpass = ""
1.upto(5) { |i| newpass << chars[rand(chars.size-1)] }
#Get the original file name
upload=params[:upload]
name = upload['datafile'].original_filename
#license.format = File.extname(name)
#calculate license ID and location
#license.location = './public/licenses/' + sessid + newpass + name
#Save the license file
#Fileupload.save(params[:upload], #license.location)
File.open(#license.location, "wb") { |f| f.write(upload['datafile'].read) }
#Set license ID
#license.license_id = sessid + newpass
#Save the license
#license.save
redirect_to :action => 'show', :id => #license.id
end
I have tried this spec, but it doesnt work:
it "can upload a license and download a license" do
file = File.new(Rails.root + 'app/controllers/lic.xml')
license = HashWithIndifferentAccess.new
license[:datafile] = file
info = {:id => 4}
post :uploadLicense, {:license => info, :upload => license}
end
How can I simulate the file upload, using rspec?
You can use fixture_file_upload method to test file uploading:
Put your test file in "{Rails.root}/spec/fixtures/files" directory
before :each do
#file = fixture_file_upload('files/test_lic.xml', 'text/xml')
end
it "can upload a license" do
post :uploadLicense, :upload => #file
response.should be_success
end
In case you were expecting the file in the form of params['upload']['datafile']
it "can upload a license" do
file = Hash.new
file['datafile'] = #file
post :uploadLicense, :upload => file
response.should be_success
end
I am not sure if you can test file uploads using RSpec alone. Have you tried Capybara?
It's easy to test file uploads using capybara's attach_file method from a request spec.
For example (this code is a demo only):
it "can upload a license" do
visit upload_license_path
attach_file "uploadLicense", /path/to/file/to/upload
click_button "Upload License"
end
it "can download an uploaded license" do
visit license_path
click_link "Download Uploaded License"
page.should have_content("Uploaded License")
end
if you include Rack::Test*, simply include the test methods
describe "my test set" do
include Rack::Test::Methods
then you can use the UploadedFile method:
post "/upload/", "file" => Rack::Test::UploadedFile.new("path/to/file.ext", "mime/type")
*NOTE: My example is based on Sinatra, which extends Rack, but should work with Rails, which also uses Rack, TTBOMK
I haven't done this using RSpec, but I do have a Test::Unit test that does something similar for uploading a photo. I set up the uploaded file as an instance of ActionDispatch::Http::UploadedFile, as follows:
test "should create photo" do
setup_file_upload
assert_difference('Photo.count') do
post :create, :photo => #photo.attributes
end
assert_redirected_to photo_path(assigns(:photo))
end
def setup_file_upload
test_photo = ActionDispatch::Http::UploadedFile.new({
:filename => 'test_photo_1.jpg',
:type => 'image/jpeg',
:tempfile => File.new("#{Rails.root}/test/fixtures/files/test_photo_1.jpg")
})
#photo = Photo.new(
:title => 'Uploaded photo',
:description => 'Uploaded photo description',
:filename => test_photo,
:public => true)
end
Something similar might work for you also.
This is how I did it with Rails 6, RSpec and Rack::Test::UploadedFile
describe 'POST /create' do
it 'responds with success' do
post :create, params: {
license: {
picture: Rack::Test::UploadedFile.new("#{Rails.root}/spec/fixtures/test-pic.png"),
name: 'test'
}
}
expect(response).to be_successful
end
end
DO NOT include ActionDispatch::TestProcess or any other code unless you're sure about what you're including.
I had to add both of these includes to get it working:
describe "my test set" do
include Rack::Test::Methods
include ActionDispatch::TestProcess

Resources