• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录

Still_Walking

  • 博客园
  • 联系
  • 订阅
  • 管理

公告

View Post

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

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

本事例只为说明如何修改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

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

如果有更好的方法,还望大家赐教。

posted on 2017-02-08 19:42  limanxian  阅读(2258)  评论(0)    收藏  举报

刷新页面返回顶部
 
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3