ruby on rails 修改配置文件或修改yml文件的內容

本事例只爲說明如何修改yml文件內容。git

1、需求是怎麼樣修改yml文件內容?github

配置文件名稱爲webinfo.yml,內容爲:web

development:json

  webinfo:網站

    webtitle: 個人網站名稱ui

    keyword: 網站的關鍵字spa

production:對象

  webinfo:get

    webtitle: 上線後的網站名稱hash

    keyword:上線後的網站的關鍵字

 

2、我是怎麼作的?

個人思想是:首先取到配置文件的全部內容,把內容轉換爲json對象或hash對象,而後把某個字段的值修改成本身的內容,再把整個json或hash轉換成yml寫回到yml配置文件。

一、獲取內容並轉化爲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

二、修改某個字段的值

  在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

   這樣就把這個屬性的內容改掉了。

若是有更好的方法,還望你們賜教。

相關文章
相關標籤/搜索