ActiveHash 使用教程

ActiveHash 使用教程

active_hashA readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource项目地址:https://gitcode.com/gh_mirrors/ac/active_hash

1、项目介绍

ActiveHash 是一个简单的基类,允许您使用 Ruby 哈希作为 ActiveRecord 类模型的只读数据源。它假设每个哈希都有一个 :id 键,这通常是您需要的。ActiveHash 可以与 YAML 文件或自定义文件一起使用,作为数据源。

2、项目快速启动

安装

首先,将 ActiveHash 添加到您的 Gemfile 中:

gem 'active_hash'

然后运行 bundle install

创建模型

创建一个继承自 ActiveHash::Base 的类:

# app/models/country.rb
class Country < ActiveHash::Base
  self.data = [
    { id: 1, name: "US" },
    { id: 2, name: "Canada" }
  ]
end

使用模型

在控制器或视图中使用这个模型:

# 在控制器中
@countries = Country.all

# 在视图中
<% @countries.each do |country| %>
  <%= country.name %>
<% end %>

3、应用案例和最佳实践

关联使用

ActiveHash 支持与 ActiveRecord 模型的关联。例如,如果您有一个 Person 模型,并且它属于一个 Country

# app/models/person.rb
class Person < ActiveRecord::Base
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :country
end

使用快捷方式

由于 ActiveHash 对象通常是静态的,您可以使用快捷方式来分配一个易于记忆的字符串,而不是一个模糊的 ID 号:

# app/models/person.rb
class Person < ActiveRecord::Base
  extend ActiveHash::Associations::ActiveRecordExtensions
  belongs_to_active_hash :country, shortcuts: [:name]
end

4、典型生态项目

ActiveHash 可以与其他 Ruby on Rails 插件和 gem 一起使用,特别是在不需要数据库的情况下进行测试时非常有用。例如,它可以与 RSpec 一起使用来创建简单的测试类。

ActiveYaml

如果您想将数据存储在 YAML 文件中,可以继承自 ActiveYaml::Base 并指定路径信息:

# app/models/country.rb
class Country < ActiveYaml::Base
end

默认情况下,这个类会在与文件相同的目录中查找名为 countries.yml 的 YAML 文件。您可以更改目录或文件名:

class Country < ActiveYaml::Base
  set_root_path "config/data"
  set_filename "countries"
end

通过这些步骤,您可以快速开始使用 ActiveHash 并将其集成到您的 Rails 项目中。

active_hashA readonly ActiveRecord-esque base class that lets you use a hash, a Yaml file or a custom file as the datasource项目地址:https://gitcode.com/gh_mirrors/ac/active_hash

  • 15
    点赞
  • 15
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

陈宜旎Dean

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值