您的位置:首页 > 编程语言 > Ruby

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

2017-02-08 19:42 501 查看
本事例只为说明如何修改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

   这样就把这个属性的内容改掉了。

如果有更好的方法,还望大家赐教。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: