Wice_Grid CSV export not working - Uninitialized constant CSV::Writer - ruby-on-rails

I "inherited" a rails aplication running with ruby 1.8.7 in development.
I have a wice_grid table which I'm trying to export in CSV and in development all goes perfect.
When I push it to production, i get the following error:
uninitialized constant CSV::Writer
The production machine is running Ruby 1.9.1 and from what I read, I suppose the problem comes from there.
I've tried to put:
required 'csv'
In the controller or the model, but nothing happens, development works, production does not.
Here is the controller code:
def index
require 'csv'
#service_requests = initialize_grid(ServiceRequest,
:name => "solicitudes",
:order => "created_at" ,
:order_direction => 'desc',
:include => [:user, :service],
:enable_export_to_csv => true,
:csv_file_name => 'Listado de Solicitudes'
)
export_grid_if_requested('solicitudes' => 'service_requests') do
#Si se pulsa en exportar se exportan todos las celdas de la tabla seleccionada (con filtros aplicados)
end
end
Here is the part of the view, which calls a partial:
<%= render :partial => 'service_requests' %>
Here is the partial, cropped for making the question not too long:
<%= grid(#service_requests, :show_filters => :always) do |service_request|
[...]
service_request.column :column_name => 'Nombre' , :attribute_name => 'name', :model_class => User do |sr|
sr.user.name
end
service_request.column :column_name => 'Apellidos' , :attribute_name => 'lastName' , :model_class => User do |sr|
sr.user.lastName
end
[...]
end %>
I read this thread but didnt help me much: write csv in ruby 1.9 and CSV::Writer
Thank you all in advance!

Somewhere, that you haven't posted, you are referencing CSV::Writer. This works locally because you're using Ruby 1.8.7, but your production server is using Ruby 1.9.1. CSV::Writer was deprecated with Ruby 1.9.
From the the docs:
# * The old CSV's Reader and Writer classes have been dropped.
Step one is to upgrade your local Ruby to the same version as the server. This will give you the same error locally, which should go away once you find and remove that CSV::Writer.
The CSV docs give examples of how to use the current CSV class to accomplish what CSV::Writer used to do. Here's an example:
# == Writing
#
# === To a File
#
# CSV.open("path/to/file.csv", "wb") do |csv|
# csv << ["row", "of", "CSV", "data"]
# csv << ["another", "row"]
# # ...
# end
Upgrading Ruby will probably raise other errors. But Ruby 1.8.7 was retired in 2013 so these are problems you're going to want to fix now rather than later.
Good luck!

Related

Brakeman not skipping Gemfile.lock with --skip-files param

I'm adding Brakeman to a Rails product but I'm running into an issue. I want it to ignore my Gemfile and Gemfile.lock but when I run it with a command like
brakeman --skip-files Gemfile.lock,Gemfile
it's still touching the files. We use other systems to monitor our gems, but is it not possible to ignore the gem files completely? I can use a brakeman.ignore file of course but would prefer not to. Thanks for any assistance.
I believe this is the check to which you are referring:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/scanner.rb#L39-L40
Brakeman.notify "Processing gems..."
process_gems
The process_gems function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/scanner.rb#L131-L152
#Process Gemfile
def process_gems
gem_files = {}
if #app_tree.exists? "Gemfile"
gem_files[:gemfile] = { :src => parse_ruby(#app_tree.read("Gemfile")), :file => "Gemfile" }
elsif #app_tree.exists? "gems.rb"
gem_files[:gemfile] = { :src => parse_ruby(#app_tree.read("gems.rb")), :file => "gems.rb" }
end
if #app_tree.exists? "Gemfile.lock"
gem_files[:gemlock] = { :src => #app_tree.read("Gemfile.lock"), :file => "Gemfile.lock" }
elsif #app_tree.exists? "gems.locked"
gem_files[:gemlock] = { :src => #app_tree.read("gems.locked"), :file => "gems.locked" }
end
if gem_files[:gemfile] or gem_files[:gemlock]
#processor.process_gems gem_files
end
rescue => e
Brakeman.notify "[Notice] Error while processing Gemfile."
tracker.error e.exception(e.message + "\nWhile processing Gemfile"), e.backtrace
end
The AppTree::exists? function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/app_tree.rb#L82-L84
def exists?(path)
File.exist?(File.join(#root, path))
end
The GemProcessor::process_gems function is defined here:
https://github.com/presidentbeef/brakeman/blob/master/lib/brakeman/processors/gem_processor.rb#L11
...lots of code...
I don't see any code that would skip this functionality if a certain switch is provided to brakeman. It also looks like the AppTree::exists? function does not take into account if a file was provided to the --skip-files option.
Unfortunately, I believe the current answer is that you can not ignore the gem files completely.
You could create a PR to do what you want and see if the Brakeman team includes it in the next build:
https://brakemanscanner.org/docs/contributing/
Let us know if you discover a way to solve your problem.

There's an easy way to load csv rows into an Heroku hosted app?

I have some csv exported rows of data that I need to load into a Rails 2.3.8 app.
The csv data is already in the perfect format for the app that I'm hosting on Heroku.
Is there an easy way to do it?
Thanks,
Augusto
I have had success with something like this:
require 'csv'
CSV.foreach(Rails.root.to_s+"/db/calseed_test1.csv") do |row|
Calevent.create(
:caldate => row[0],
:caltime => row[1],
:callocation => row[2],
:caldescription => row[3]
)
end
You could use Ruby's built-in CSV library to read your data into an array, which you can then do whatever you need to with:
CSV.foreach("path/to/file.csv") do |row|
# use row here...
# For example, if you had users in a CSV file like "username,email" you could do:
User.create(:username => row[0], :email => row[1])
end
Yes, there is a very simple way.
Upload the file to gist or anywhere publically accessible.
Use open-uri to load it in any console of your choice.
csv_file = open('https://gist.githubusercontent.com/gauravsaini23/84f9592bbc7cf444e869f8c67321a086/raw/84f7dc0c9d0770a30d28072e05527d1071870042/sample.csv') {|f| f.read}
You have all your required data.
csv = CSV.new(csv_file)
pry(main)> csv.first
=> ["Name", " Purpose"]

ArgumentError on application requests

I've written a basic Rails 3 application that shows a form and an upload form on specific URLs. It was all working fine yesterday, but now I'm running into several problems that require fixing. I'll try to describe each problem as best as I can. The reason i'm combining them, is because I feel they're all related and preventing me from finishing my task.
1. Cannot run the application in development mode
For some unknown reason, I cannot get the application to run in development mode. Currently i've overwritten the production.rb file from the environment with the settings from the development environment to get actuall stacktraces.
I've added the RailsEnv production setting to my VirtualHost setting in apache2, but it seems to make no difference. Nor does settings ENV variable to production.
2. ArgumentError on all calls
Whatever call I seem to make, results in this error message. The logfile tells me the following:
Started GET "/" for 192.168.33.82 at
Thu Apr 07 00:54:48 -0700 2011
ArgumentError (wrong number of
arguments (1 for 0)):
Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_trace.erb
(1.0ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb
(4.1ms) Rendered
/usr/lib/ruby/gems/1.8/gems/actionpack-3.0.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb
within rescues/layout (8.4ms)
This means nothing to me really. I have no clue what's going wrong. I currently have only one controller which looks like this:
class SearchEngineController < ApplicationController
def upload
end
def search
#rows = nil
end
# This function will receive the query string from the search form and perform a search on the
# F.I.S.E index to find any matching results
def query
index = Ferret::Index::Index.new :path => "/public/F.I.S.E", :default_field => 'content'
#rows = Array.New
index.search_each "content|title:#{params[:query]}" do |id,score, title|
#rows << {:id => id, :score => score, :title => title}
end
render :search
end
# This function will receive the file uploaded by the user and process it into the
# F.I.S.E for searching on keywords and synonims
def process
index = Ferret::Index::Index.new :path => "public/F.I.S.E", :default_field => 'content'
file = File.open params[:file], "r"
xml = REXML::Document.new file
filename = params[:file]
title = xml.root.elements['//body/title/text()']
content = xml.root.elements['normalize-space(//body)']
index << { :filename => filename, :title => title, :content => content}
file.close
FileUtils.rm file
end
end
The routing of my application has the following setup: Again this is all pretty basic and probably can be done better.
Roularta::Application.routes.draw do
# define all the url paths we support
match '/upload' => 'search_engine#upload', :via => :get
match '/process' => 'search_engine#process', :via => :post
# redirect the root of the application to the search page
root :to => 'search_engine#search'
# redirect all incoming requests to the query view of the search engine
match '/:controller(/:action(/:id))' => 'search_engine#search'
end
If anyone can spot what's wrong and why this application is failing, please let me know. If needed I can edit this awnser and include additional files that might be required to solve this problem.
EDIT
i've managed to get further by renaming one of the functions on the controller. I renamed search into create and now I'm getting back HAML errors. Perhaps I used a keyword...?
woot, finally found the solutions....
Seems I used keywords to define my actions, and Rails didn't like this. This solved issue 2.
Issue 1 got solved by adding Rails.env= 'development' to the environment.rb file

FasterCSV (seemingly) not working in Rails 3.0.5

I am trying to export data from a rails app and have the user download a CSV file when they hit a certain controller#action.
I found this article and used the sample code exactly.
http://oldwiki.rubyonrails.org/rails/pages/HowtoExportDataAsCSV
I do, in fact, get a CSV file, but within it, there is only one line of output:
#<Proc:0x00000001032c6808#/PATH_CRAP/app/controllers/reports_controller.rb:35>
Here are lines 35, 36 and 37 from the file in question.
render :text => Proc.new { |response, output|
csv = FasterCSV.new(output, :row_sep => "\r\n")
yield csv
I am using Rails 3.0.5 and added the following to my Gemfile:
gem 'fastercsv'
What gives?
render :text => proc {...} does not work in Rails 3. For the replacement, see this question.

Feedzirra in Rails 3

I am trying to get feedzirra running on rails 3, I tried by some methods I have found on the internet.
This is in my gemfile:
source 'http://gems.github.com'
gem 'loofah', '1.0.0.beta.1'
group :after_initialize do
gem 'pauldix-feedzirra'
end
And i've out this after bundle.setup in root.rb
Bundler.require :after_initialize
And this is the code in my model (movie.rb)
class Movie < ActiveRecord::Base
def self.import_from_feed
feed = Feedzirra::Feed.fetch_and_parse("url-to.xml")
add_entries(feed.entries)
end
private
def self.add_entries(entries)
entries.each do |entry|
unless exists? :guid => entry.id
create!(
:title => entry.title,
:synopsis => entry.synopsis,
:cover => entry.cover,
:duration => entry.duration,
:channel => entry.channel,
:imdb_rating => entry.imdb_rating,
:imdb_votes => entry.imdb_votes,
:imdb_id => entry.imdb_votes
)
end
end
end
end
I try to run the import_from_feed function from the console and I keep getting this error:
>> Movie.import_from_feed
NameError: uninitialized constant Movie::Feedzirra
from /Users/myname/Ruby/appname/app/models/movie.rb:3:in `import_from_feed'
from (irb):1
Can someone help me out? Been trying for ages now!
Two things:
Just add the gem, not under :after_initialize
Use the feedzirra gem, not the old pauldix-feedzirra one.

Resources