将bash脚本的输出解析为Rails

时间:2016-01-21 20:15:44

标签: ruby-on-rails ruby bash

我有另一个stackoverflow问题的bash脚本来获取我所有的串行连接设备:

#!/bin/bash
for sysdevpath in $(find /sys/bus/usb/devices/usb*/ -name dev); do
    (
        syspath="${sysdevpath%/dev}"
        devname="$(udevadm info -q name -p $syspath)"
        [[ "$devname" == "bus/"* ]] && continue
        eval "$(udevadm info -q property --export -p $syspath)"
        [[ -z "$ID_SERIAL" ]] && continue
        echo "{name: '/dev/$devname', id_serial: '$ID_SERIAL'}"
    )
done

我试图将它们解析为一个对象数组,以便在Rails视图上迭代并显示它们。输出是这样的:

{name: '/dev/input/event16', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/input/mouse2', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/hidraw0', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/usb/hiddev3', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/input/event17', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/hidraw1', id_serial: 'Logitech_USB_Receiver'}
{name: '/dev/input/event15', id_serial: 'SunplusIT_INC._Integrated_Camera'}
{name: '/dev/media0', id_serial: 'SunplusIT_INC._Integrated_Camera'}
{name: '/dev/video0', id_serial: 'SunplusIT_INC._Integrated_Camera'}

在Rails控制台中,这是输出:

2.2.4 :001 > `./lib/scripts/get_serial.sh`
 => "{name: '/dev/input/event16', id_serial: 'Logitech_USB_Receiver'}\n{name: '/dev/input/mouse2', id_serial: 'Logitech_USB_Receiver'}\n{name: '/dev/hidraw0', id_serial: 'Logitech_USB_Receiver'}\n{name: '/dev/usb/hiddev3', id_serial: 'Logitech_USB_Receiver'}\n{name: '/dev/input/event17', id_serial: 'Logitech_USB_Receiver'}\n{name: '/dev/hidraw1', id_serial: 'Logitech_USB_Receiver'}{name: '/dev/media0', id_serial: 'SunplusIT_INC._Integrated_Camera'}\n{name: '/dev/video0', id_serial: 'SunplusIT_INC._Integrated_Camera'}\n"

所以我试图在我的控制器中解析它:

def index
   @devices = `./lib/scripts/get_serial.sh`.strip.gsub(" ","").split("\n")
end

如果我@devices[0],则结果为:=> "{name:'/dev/input/event16',id_serial:'Logitech_USB_Receiver'}"

最后,在视图中:

<ul>
  <% @devices.each do |device| %>
    <li><%= device %> </li>
  <% end %>
</ul>

显示所有设备,但如果我<%= device.name %>我收到错误或<%= device['name'] %>我收到“name”字样。

我的问题很简单。有没有更好的方法来处理:name:id_serial作为典型变量(迭代数组并打印它们)?

1 个答案:

答案 0 :(得分:1)

而不是:

@devices = `./lib/scripts/get_serial.sh`.strip.gsub(" ","").split("\n")

尝试使用:

@devices = `./lib/scripts/get_serial.sh`.split("\n").map {|hash_string| eval(hash_string)}

有关详细说明,请查看How do I convert a String object into a Hash object?