简体   繁体   中英

Ruby ERB how to create list of mount points

I am trying to use ERB templating to dynamically create a list of mount points for filesystems, to be monitored for disk usage by Nagios. I am having trouble figuring out the exact syntax for ERB, I have it working in straight Ruby.

Here is what I have tried for ERB

 <% @str = `df -h`; @str.scan(/\/[\w\/]+$/){|m| -%><%= -p @m %><% unless m.match(/\/dev|\/proc/)};puts %>

Here is my code, and desired output working in the Ruby CLI:

ruby -e '
str = `df -h`
str.scan(/\/[\w\/]+$/){|m| print "-p #{m} " unless m.match(/\/dev|\/proc/)};puts'
-p /net -p /home -p /Network/Servers <-- Output

First of all, you don't need to run those in the template . You probably have some ruby code lauching the template (like a Rails controller or a Sinatra class). You can put your code there, and store the output to show in the template (example assuming rails).

Second, you don't want to use print or puts (as those would output toward the terminal, not the template), but to store the output in a variable.

The controller:

class MountPointsController < ApplicationController
  def index
    @output = ""
    str = `df -h`
    str.scan(/\/[\w\/]+$/){|m| output << "-p #{m} " unless m.match(/\/dev|\/proc/)};output << "\n"
  end
end

The template is then as simple as (note the '<%=' that means "output the result in the template):

<%= @output %>

Even if I would recommend against, here is a sample with all the code in the template:

<% @output = "" %>
<% str = `df -h` %>
<% str.scan(/\/[\w\/]+$/){|m| output << "-p #{m} " unless m.match(/\/dev|\/proc/)};output << "\n" %>
<%= @output %>

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