sturoid
sturoid

Reputation: 2711

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.

Upvotes: 1

Views: 2201

Answers (3)

the Tin Man
the Tin Man

Reputation: 160551

"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.

Upvotes: 0

atmaish
atmaish

Reputation: 2613

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. :)

Upvotes: 0

Prakash Murthy
Prakash Murthy

Reputation: 13067

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.

Upvotes: 1

Related Questions