本事例只為說明如何修改yml文件內容。
一、需求是怎么樣修改yml文件內容?
配置文件名稱為webinfo.yml,內容為:
development:
webinfo:
webtitle: 我的網站名稱
keyword: 網站的關鍵字
production:
webinfo:
webtitle: 上線后的網站名稱
keyword:上線后的網站的關鍵字
二、我是怎么做的?
我的思想是:首先取到配置文件的所有內容,把內容轉換為json對象或hash對象,然后把某個字段的值修改為自己的內容,再把整個json或hash轉換成yml寫回到yml配置文件。
1、獲取內容並轉化為json或hash
獲取文件內容的方式有很多,這里介紹兩種方式:使用YAML.load(File.open(filepath))或YAML.load_file(filepath)和使用Gem包settingslogic(settingslogic的使用請參考:https://github.com/binarylogic/settingslogic)
這里我使用settingslogic這種方式:新建一個類(比如在models文件夾下),類名:Webinfo,內容為
class Webinfo< Settingslogic
PATH = "#{Rails.root}/config/webinfo.yml"
source PATH
namespace Rails.env
end
在controller里的使用Webinfo.webinfo或Webinfo["webinfo"]來獲取到內容,代碼如下:
def get_webinfo
info = Webinfo["webinfo"]
puts info.inspect
title = info["webtitle"]
puts title
end
2、修改某個字段的值
在Webinfo類新增保存方法:
require 'yaml/store'
class Webinfo< Settingslogic
PATH = "#{Rails.root}/config/webinfo.yml"
source PATH
namespace Rails.env
def self.save(content)
store = YAML::Store.new PATH
store.transaction do
store[Rails.env]["webinfo"] = content.to_hash
end
end
end
在controller里的新建修改的方法,代碼如下:
def update_webinfo
info = Webinfo["webinfo"] # 獲取
info["webtitle"] = "新的網站名稱"
Webinfo.save(info) # 保存
end
這樣就把這個屬性的內容改掉了。
如果有更好的方法,還望大家賜教。