首页
/ YAML Record 技术文档

YAML Record 技术文档

2024-12-26 21:54:10作者:宣海椒Queenly

本文档将详细介绍如何安装、使用以及通过API操作 YAML Record 项目。YAML Record 是一个符合 ActiveModel API 的数据持久化库,可以用于轻松地管理数据,类似于使用 ActiveRecord。

1. 安装指南

安装 YAML Record 使用 RubyGems:

gem install yaml_record

或者将 gem 添加到你的 Gemfile:

# Gemfile
gem 'yaml_record'
# 如果你在使用 Rails 3.1
gem 'yaml_record', :git => "git@github.com:Nico-Taing/yaml_record.git", :branch => "rails31"

执行以下命令安装:

bundle install

2. 项目使用说明

声明

创建任何 Ruby 对象并继承自 YamlRecord::Base 以定义类型:

class Post < YamlRecord::Base
  # 声明属性
  properties :title, :body, :user_id

  # 声明适配器(默认为 local)
  adapter :local # 或者 :redis
  
  # 声明源文件路径
  source Rails.root.join("config/posts")
end

使用这个新对象与使用任何 ActiveRecord 对象相同。

检索

检索集合:

Post.all => [@p1, @p2]

通过 id 检索项目:

Post.find("a1b2") => @p1

通过属性检索:

Post.find_by_attribute(:title, "某个标题") => @p

创建

初始化帖子:

@p = Post.new(:title => "...", :body => "...", :user_id => 5)
@p.save

创建帖子:

@p = Post.create(:title => "...", :body => "...", :user_id => 6)

更新

使用预期的方法更新属性:

@p.update_attributes(:title => "新标题")

销毁

销毁给定记录:

@p.destroy

访问

访问属性:

@p = Post.find("a1b2")
@p.title => "..."

分配属性:

@p.title = "新标题"
@p.save

回调

创建回调:

class Submission < YamlRecord::Base
  # ...
  before_create :do_something # 或 before_save, before_destroy, ...

  def do_something
    # 这里做些事情
  end
end

3. 项目API使用文档

YAML Record 提供了以下几个关键方法供使用:

  • all: 检索所有记录。
  • find(id): 通过 id 检索记录。
  • find_by_attribute(attribute, value): 通过属性和值检索记录。
  • new(attributes): 初始化新记录。
  • create(attributes): 创建新记录并保存。
  • update_attributes(attributes): 更新记录属性。
  • destroy: 销毁记录。

4. 项目安装方式

YAML Record 的安装方式已在安装指南中详细说明,可通过 RubyGems 或添加到 Gemfile 并执行 bundle install 来安装。

以上是 YAML Record 的技术文档,希望能帮助您更好地理解和使用这个项目。

登录后查看全文
热门项目推荐