简体   繁体   中英

Read strings Array from javascript file in Rails

I have a file countries.js which contains an array of countries and I would like to read and use this in my rails app also as an array of strings.

The content of js file:

export default [
 'United States',
 'Canada',
  ...
 ];

How can I do this?

You can do this:

 countries = File.read('countries.js')

 countries.gsub(/export default/,"").
 split("\n").map{|c|c.gsub(/[^a-z A-Z]/,"")}.
 map(&:strip).
 reject(&:empty?)

My suggestion would be to convert this file to a JSON file.

contries = File.read('countries.json')
countries = JSON.parse(countries)

You might need to further parse it with JSON so that you can convert string to a collection data structure.

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