简体   繁体   中英

Ruby/Rails - open file in browser from file path string

I have a rails app where I am listing all css and js in a browser that are in the project folder. I have this code to list the files:

<% @files = Dir['**/*.{js,css}'] %>
<% @files.sort.each do |d| %>
  <li><%= d %></li>
<% end %>

How can I make those path strings links to the files so that they can be opened in the browser and edited? Thank you for your help.

Assuming all the js & css files to be listed are under the /public subfolder of the application, the following should work to display the files in the browser:

<% @files = Dir['**/*.{js,css}'] %>
<% @files.sort.each do |file_name| %>
  <% file_name = file_name.gsub( 'public', '' ) %>
  <li><%= link_to("public" + file_name, file_name) %></li>
<% end %> 

Got inspired from this : http://railsforum.com/viewtopic.php?id=20097

NOTE: This only makes the files viewable in the browser; not sure if the files can be edited directly from the browser.

Since .js, .css are plain text files, you can just extract the text in a string and display in pretty format.

data = File.read("/path/to/file")

I dont think you can edit a file in your browser. One way to do that would be to invoke an editor to open the file.

Update : Opening a file in editor

server_cmd = "gedit path/to/file"
res = `#{server_cmd}`

Place this code block in an action that would be called when you click the file link in your view. Should open the gedit editor and you're good to go. :)

" Is there a good in-browser code editor? " is a pre-existing Stack Overflow question dealing with that question. Look through the related questions on that page's bottom right for more ideas.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM