2016-01-21 67 views
1

我從另一個計算器問題bash腳本讓我所有的串行連接的設備:輸出解析到Rails

#!/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:id_serial作爲典型變量(迭代數組並打印它們)?

回答

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?

+0

不幸的是'設備[ '名']'在視圖中顯示爲空/空白值。 – ftshtw

+0

@ChrisV。爲什麼它應該呢?試試''device [:name]'' –

+0

如果你不解釋這一點,我會辭去工作,成爲麪包師或垃圾回收員。 – ftshtw