I am pretty new to ruby and RoR, so please pardon my noviceness.
I want to print complete list of the folders inside a given directory in my rails application. Following is the code I use in my show.html.erb file.
<%= dir = Dir.entries(path_to_my_directory)
dir.each do |folder|
puts folder
end %>
The Dir.entries method return an array, containing the names of all the folders inside the specified directory. I traverse this array and print every single value.
But on my application, this prints the complete array like mentioned below.
[".", "metadata.rb", "attributes", "libraries", "CHANGELOG.md", "recipes", "..", "files", "templates", "providers", "resources", "definitions", "README.md"]
I tried other ways to traverse an array but the output remains the same. This code when run individually produces the expected output, but when ran from inside my view, it doesn't seem to work. Any suggestions on where I might be going wrong.
Thanks in advance.
You can't use puts in erb. Find the difference between <% %>(processing the Ruby code) and <%= %>(processing and outputs the enclosed Ruby code). What you wanted to do is:
<%
dir = Dir.entries(path_to_my_directory)
dir.each do |folder|
%>
<%= folder %>
<% end %>
Related
I am developing my first Ruby On Rails project and I have the following question.
Is it possible to display a window with the contents of a folder so I can select a file? For example, images from the "app/assets/images" project folder.
I have searched in Google and rubygems.org but have not found anything.
Respectfully,
Jorge Maldonado
You could write a controller method and associated view that scan over a folder and output the contents. Here's an example.
Controller:
def folder
#files = Dir.open(Rails.root.join('public', 'images'))
end
View:
<table>
<% #files.each do |file| %>
<tr><td><%= link_to file, file_path(file) %></td></tr>
<% end %>
</table>
Note that file_path is assumed to be some route defined in routes.rb which accepts a file name and allows the user to view/open/download that file.
Here's a gem that also gives similar functionality:
https://github.com/furkancelik/fcfinder
I'm working on a web application that has a view where data is fetched and parsed from a text file (the textfile is only available at the backend, not to the user). I've written a function that takes in the text file and converts it to an array of strings, it's called txt_to_arr. Then I have another function line_fetcher which just calls txt_to_arr and outputs a random string from the array.
In my view, I call the controller's function as so: <% line_fetcher %>.
I've put both txt_to_arr and line_fetcher into the view controller's helper rb file, and when I run rails s, the random string is not rendered at all. I've also tried <% puts line_fetcher %>
I've checked in Bash that the function does output random strings from the text file, so the function does work correctly. Also, the text file being parsed is in the public folder. Does anyone have an idea why this might be?
Thanks a lot!
Try placing the code in the controller and assigning the output to a variable using
a=`line_fetcher` (note the backtics) as detailed at
http://rubyquicktips.com/post/5862861056/execute-shell-commands
and then <%= a %> in your view.
and place the file in the root of your rails app
Simple erb like <%= line_fetcher %> would work good for simple variables.
But if you want output of any model/database instance then do:
<%= ModelName.first.inspect %>
Note the inspect word.
And in case of using HAML do:
=ModelName.first.inspect
In ERB: The <% %> signify that there is Ruby code here to be interpreted. The <%= %> says interpreted and output the ruby code, ie display/print the result.
So it seems you need to use the extra = sign if you want to output in a standard ERB file.
<%= line_fetcher %>
Use <%= %> to output something in your view, so:
<%= line_fetcher %>
I'm trying to write a simple RoR app that lists all directories in a specific path then allows me to click that file or directory to either open the file or open the directory. I'm using the following code which works to list the directories but I can't figure out how to open the file or directory from here. When clicking the directory I get a "No route matches [GET] "/selected file" error.
controller
#file = Dir.foreach ("/specifiedpath/")
view
<% #file.each do |file| %>
<tr>
<td><%= link_to file, file %></td>
</tr>
<% end %>
Any help would be appreciated!
You need something in your routes.rb that looks like this:
get '/browse/*path' => 'browse#show', as: :browse
In your browse_controller, you'll want a show action that does something like:
class BrowseController < ApplicationController
def show
#path = params[:path] || '/some/default'
#files = Dir.foreach(path)
end
Finally, in your browse/show.html.haml (I prefer HAML, sorry) view, something like:
- #files.each do |file|
%tr
%td= link_to file, browse_path(File.join(#path, file))
(Pardon me if it all doesn't work outright—haven't time to fully test a fleshed out solution right now—but I can delve into it a little more if you have trouble getting it to work yourself.)
I'm attempting to upload a csv file, parse it, and spit out a file for S3 or just pass to view. I use a file_field_tag to upload the csv. I thought file_field_tag passes an object that is a subclass of IO and would have all ruby IO methods such as "each_line". I can call "read" on the object (method of IO class) but not "each_line"... so how can I iterate over each line of a file_field_tag upload?
create method of my controller as:
#csv_file = params[:csv_file]
My show view which throws a no "each_line" method error:
<% #csv_file.each_line do |line| %>
<%= line %>
<% end %>
Yet I can use
<%= #csv_file.read(100) %>
I'm really confused what methods a file_field_tag upload params[] has... each_line, gets don't work... I can't seem to find a list of what I can use.
EDIT
I worked around this by doing:
#csv_file = params[:csv_file].read.to_s
then iterated through with:
<% #sp_file.each_line do |line| %>
<%= line %>
<% end %>
EDIT 2
The file being uploaded has repeats the header after lines which don't contain a comma (don't ask)... So I find lines without a comma and call .gets (in my rb script independent of rails). Unfortunately I get an error about gets being a private method I can't call. Which goes back to my initial issue being. Aren't files a sub class of IO with IO methods like read_lines & gets?
#file_out = []
#file_in.each_line do |line|
case line
when /^[^,]+$/
#comp = line.to_s.strip
comp_header = #file_in.gets.strip.split('')
#file_out.push(#comp)
end
end
When you post a 'file_field' , the param returned to the controller has some special magic hooked in.
I.e. in your case you could this
<%= "The following file was uploaded #{params[:csv_file].original_filename}" %>
<%= "It's content type was #{params[:csv_file].content_type}" %>
<%= "The content of the file is as follows: #{params[:csv_file].read}" %>
So those are the three special methods you can call on params[:csv_file], or any params posted as the result of a successful 'file_field_tag' or 'f.file_field' in a view
Just remember that those are the three extra special things you can to to a param posted as a result of a file_field:
original_filename
content_type
read
You've clearly figured out how to do the read, the original_filename and content_type may help you out in the future.
EDIT
OK, so all you have is the read method, which will read the contents of the file uploaded.
contents = params[:csv_file].read
So now contents is a string containing the contents of the file, but nothing else is known about that file EXCEPT that it's a csv file. We know that csvs are delimited with '\r' (I think, I've done a lot of work with parsing csv's, but I'm too lazy to go check)
so you could do this:
contents = params[:csv_file].read
contents.split("\r").each do |csvline|
???
end
EDIT 2
so here is the take away from this post
When you post a file_field to a controller, the most common thing to do with the contents of the uploaded file is 'read' it into a ruby String. Any additional processing of the uploaded contents must be done on that ruby String returned from the 'read'.
In this particular case, if the uploaded file is ALWAYS a CSV, you can just assume the CSV and start parsing it accordingly. If you expect multiple upload formats, you have to deal with that, for example:
contents = params[:csv_file].read
case params[:csv_file].content_type
when 'txt/csv'
contents.split("\r").each do |csvline|
???
end
when 'application/pdf'
???
end
I just took a look at http://ruby-doc.org/ruby-1.9/classes/ERB.html as well as http://ruby-doc.org/ruby-1.8/classes/ERB.html. I saw that the following is supported both in 1.8 and 1.9.
% a line of Ruby code
But after a tried it in a line of
% end ### changed from <% end %>
the browser simply shows % end in plain... Wondering what's the problem here?
(updated) another question, it seem when comment like #blabla appears in <%= %>, rails will get an error, any idea?
my code for another question:
<%= #page_title || 'Pragmatic Bookshelf' #magic #page_title; a if a is true, else b%>
Thanks
This is a comment in ERB:
<%# Where is pancakes house? %>
whereas this is an error:
<%= # I'll cook you some eggs, Margie. %>
You cannot combine a comment and the <%= %> syntax.
In the documentation you linked to, you might notice the optional -- see ERB.new note in here:
% a line of Ruby code -- treated as <% line %> (optional -- see ERB.new)
And then, ERB.new has this to say:
If *trim_mode* is passed a String containing one or more of the following modifiers, ERB will adjust its code generation as listed:
% enables Ruby code processing for lines beginning with %
So you probably don't have a *trim_mode* in your ERB.new options.
If *trim_mode* is passed a String containing one or more of the following modifiers, ERB will adjust its code generation as listed:
% enables Ruby code processing for lines beginning with %