I have a samba server on our network which contains a number of directories, one of the directories is full of .xls Microsoft Excel documents.
What I am trying to achieve is basically a list of the files within the remote directory which I can then mash up into a link which includes the remote IP. The end result is basically a live table of the files in the directory which the user can click on to open the file they need.
I've read about the following method of doing something similar:
basedir = '.'
files = Dir.glob("*.xls")
What I am trying to work out, is how do I make the basedir a remote IP and also how I would build this into my model/controller.
Ideally I would like to do something like this:
file_controller.rb
class FilesController < ApplicationController
basedir = '192.168.1.1/files/path/to/xlsdocuments/'
def index
#xls_files = Dir.glob("*.xls")
respond_to do |format|
format.html # index.html.erb
format.json { render json: #articles }
end
end
This would then allow me to loop through the #xls_files in my view.
Is this even remotely possible?
UPDATE
Using the above code in my controller as follows, I don't get any errors but I can't figure out how to display the file names:
class DocumentsController < ApplicationController
before_filter :authorize, only: [:new, :edit, :update]
basedir = '192.168.1.1/common/'
# GET /documents
# GET /documents.json
def index
#documents = Document.all
#xls_files = Dir.glob("*.xls")
#xls_files = #xls_files.split('\n')
respond_to do |format|
format.html # index.html.erb
format.json { render json: #documents }
end
end
I'm looping through the file names using the following in my view:
<% #xls_files.each do |xls| %>
file name
<% end %>
This outputs file name. Any idea how I output the actual filename?
For anyone else that may want to do this, these are the steps I took to get it working:
Mount the remote folder locally.
fusermount -u ~/yourmountdirectory
List the contents of the local (remote) directory
#xls_files = Dir.glob("/home/danny/nurserotas/*")
3.Output list in view of the files
<ul>
<% #xls_files.each do |xls| %>
<li><%= xls %></li>
<% end %>
</ul>
Did you try to use a command line like this :
#xls_files = `ssh 192.168.1.1 'ls /path/to/dir *.xls'`
#xls_files = #xls_files.split('\n')
Related
I have the following code in my controller that exports a csv file
...
def export
#filename = 'users.csv'
#output_encoding = 'UTF-8'
#users = User.active_users #not the actual scope but this only returns active
respond_to do |format|
format.csv
end
end
...
And I have the following in my spec
it "should only return active users"
get :export, :format => :csv
# i want to check that my mocked users_controller#export is only returning the active users and not the inactive ones
end
response.body is empty in this test when i check it. How would I go about getting the csv file in the spec that is downloaded when this action is hit in a browser so that i can check the result? I've hit a bit of a wall trying to figure this out.
Thanks for any help you can provide.
A test that checks that a CSV file is being created is as follows, assuming that the controller action is at 'csv_create_path'
it 'should create a CSV file ' do
get csv_create_path
response.header['Content-Type'].should include 'text/csv'
end
You sort of specify that CSV format is supported, but not what the contents should be. You could do
respond_to do |format|
format.csv do
render text: File.read(#filename)
end
end
to actually render that CSV file.
If you also have a normal HTML formatted view for the same data, you would simply have
respond_to do |format|
format.html
format.csv do
render text: File.read(#filename)
end
end
assuming you have setup appropriate instance variables for the HTML view before.
I'm having an unusual problem in an application I am developing.
I am writing a controller/view to generate a sitemap.xml resource. It works perfectly the first time I test it by viewing it in the browser.
However the second time, when I refresh the view, no page results are returned and the sitemap is effectively empty.
If I make a change to the code. It could be as little as adding a blank line, or removing it, then the sitemap is correctly generated the first time. Any additional refreshes are empty.
This is the code:
The sitemap controller
class SitemapController < ApplicationController
layout nil
def index
#pages = Page.where(:publish => true)
#base_url = "http://#{request.host_with_port}"
headers['Content-Type'] = 'application/xml'
def index
respond_to do |format|
format.xml
end
end
end
end
Here is sitemap.xml.erb
<?xml version="1.0" ?>
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
<% #pages.each do |page| %>
<url>
<loc><%= "#{#base_url}/#{page.permalink}" %></loc>
<lastmod><%= page.updated_at %></lastmod>
<priority>0.5</priority>
</url>
<% end unless #pages.nil? %>
</urlset>
and the route
match "/sitemap.xml", :to => "sitemap#index", :defaults => {:format => :xml}
The odd thing is that it seems to be in the query in the controller.
#pages = Page.where(:publish => true)
This returns nil on consecutive attempts, but a similar query in other parts of the app works every time. I have tried using alternative methods such as Page.all, and Page.find :all but the problem persists.
I also uploaded this to the app on Heroku, wondering if it was something in my environment, but it happens there also.
Your SitemapController#index method is redefining itself. To clarify the problem:
def fn
def fn
2
end
1
end
fn
# => 1
fn
# => 2
Try instead:
class SitemapController < ApplicationController
layout nil
def index
#pages = Page.where(:publish => true)
#base_url = "http://#{request.host_with_port}"
headers['Content-Type'] = 'application/xml'
respond_to do |format|
format.xml
end
end
end
Also, the sitemap_generator gem works rather well.
So I have one layout for 2 mail actions: signup_email and change_password
def signup_email(user, url)
#user = user
#url = url
mail(to:user.username, subject:"Welcome to Clubicity!", template_path: "mail_templates", template_name: "system")
end
def change_password(username,url)
#url = url
mail(to:username,subject:"Clubicity - password recovery", template_path: "mail_templates", template_name: "system")
end
I managed to get the one layout for this 2 actions, but now in this layout I need to render 2 different partials depending on what action is called, signup or change_pwd..
I've looked in RailsGuides and api.rubyonrails.org and they say only about templates.
Please, need help with this.
got it using mail layouts like this
def change_password(username,url)
#url = url
mail(to:username,subject:"Clubicity - password recovery") do |format|
format.html { render :layout => 'mail_templates/system'}
end
end
def signup_email(user, url)
#user = user
#url = url
mail(to:user.username, subject:"Welcome to Clubicity!") do |format|
format.html { render :layout => 'mail_templates/system'}
end
end
and in the layout just put <%= yield %>
and rock'n'roll!
So, you want to use one file for different actions. Of course you have to define actions in templates.
I propose to make one view file for each action.
For using one layout just add <%= render 'email_header' %> to the top and <%= render 'email_footer' %> to the bottom of each view. Also make _email_header.html.erb and _email_footer.html.erb with appropriate markup.
I've tryed the solution of following example: In Rails, how do you render JSON using a view?
But my problem is that the database already has a JSON string saved, I pull the json string and then I should be able to display the JSON file in the the view.
I'm using this because an android tablet should be able to visit the same url but depending on its settings (send by a POST) a different JSON file should be displayed, the android tablet then fetches the json and use it to configure some options.
So I already have a full working json file, i'm looking for a way to display it in a view (without rendering html tags and other stuff). I tryed the following (yes I've added respond_to :json) :
# def show_json (#config is the record, #config.json_config is the actual json configuration file
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json
end
Then my view I have
#show_json.json.erb
<%= #config.config_json %>
Then the HTML I get to see (no errors are given)
<html><head><style type="text/css"></style></head><body></body></html>
Thanks!
EDIT
I'm using rails 3.2.3
Here is my routes (only relevant parts)
match '/events/config', to: "events#show_json", as: :show_json
resources :events do
member do
get :select_item
get :category
end
end
Then also the controller (partial)
respond_to :html, :json, :js
def show_json
#terminal_id = params["mac"]
terminal_id = "3D:3D:3D:3D:3D:3D"
event = current_user.events.where("date(endtime) > ? AND date(starttime) < ?", Time.now.to_s, Time.now.to_s).first
if event.nil?
# Nothing got returned so we use the default event
event = current_user.events.where('"default" = ?', true).first
end
logger.info "MAC: #{terminal_id}"
terminal = current_user.terminals.where(serial: terminal_id).first
logger.info "Terminal: #{terminal.attributes.inspect}"
logger.info "#{event.attributes.inspect}"
#config = event.et_relationships.where(terminal_id: terminal).first
logger.info "CONFIG #{#config[:config_json]}"
respond_to do |format|
format.json { render json: #config[:config_json] }
end
end
Use render:
#config = event.et_relationships.where(terminal_id: terminal).first
respond_to do |format|
format.json { render json: #config }
end
And then you have path /:model/:action.json.
My controller sends a ZIP file:
def index
respond_to do |format|
format.html { render :text => open("tmp/test1.zip", "rb").read }
end
end
PROBLEM: the ZIP is received as text shown in the browser.
I would like it to come as a download.
Note: I wrote format.html because when I write format.zip I get uninitialized constant Mime::ZIP. That is probably part of the problem.
You can register your own mime type:
Mime::Type.register "application/zip", :zip
def index
respond_to do |format|
format.html { ... } #do whatever you need for html
format.csv { ... } #do whatever you need for csv
format.zip { send_file 'your_file.zip' }
end
end
have a look here:
http://weblog.rubyonrails.org/2006/12/19/using-custom-mime-types
You should probably use ActionController::DataStreaming#send_file Take a look here:
http://api.rubyonrails.org/classes/ActionController/DataStreaming.html#method-i-send_file
You can skip the respond_to stuff and manually set the content type:
def index
render :file => '/full/path/to/tmp/test1.zip', :content_type => 'application/zip', :status => :ok
end
See the Layouts and Rendering in Rails guide for more information.
If you want to support .csv as well, then you could try looking at the params[:format]:
def index
if params[:format] == 'zip'
# send back the zip as above.
elsif params[:format] == 'csv'
# send back the CSV
else
# ...
end
end
And have a look at send_file as Marian Theisen suggests.
a simple solution for the user to download a file located in the application
def index
send_data File.read('/full/path/to/tmp/test1.zip'), filename: "test1.zip"
end
send_data will read your file located here /full/path/to/tmp/test1.zip and then send it as a response as a file
and your user download a file with filename test1.zip