百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
S

store_attribute

> 编程语言
开源

ActiveRecord 扩展,它为存储访问器添加类型转换

451 stars0 点赞1 次浏览
访问官网GitHub

工具介绍

ActiveRecord 扩展,它为存储访问器添加类型转换

Store Attribute

Active Record extension which adds type casting support to store accessors.

Originally extracted from the (unmerged) PR to Ruby on Rails: rails/rails#18942.

Store Attribute is built by Evil Martians, an American design and engineering consultancy for developer tools, AI, and cybersecurity startups.

Install

In your Gemfile:

ruby
# for Rails 6.1+
gem "store_attribute", "~> 1.0"

# for Rails 5+ (6 is supported)
gem "store_attribute", "~> 0.8.0"

# for Rails 4.2
gem "store_attribute", "~> 0.4.0"

Usage

You can use store_attribute method to add additional accessors with a type to an existing store on a model.

ruby
store_attribute(store_name, name, type, options)

Where:

  • store_name The name of the store.
  • name The name of the accessor to the store.
  • type A symbol such as :string or :integer, or a type object to be used for the accessor.
  • options (optional) A hash of cast type options such as precision, limit, scale, default. Regular store_accessor options, such as prefix, suffix are also supported.

Type casting occurs every time you write data through accessor or update store itself and when object is loaded from database.

Note that if you update store explicitly then value isn't type casted.

Examples:

…

You can also specify type using usual store_accessor method:

ruby
class SuperUser  { 2.days.from_now }
end

Date.current #=> 2022-03-17

user = User.new
user.name #=> "Joe"
user.expired_at #=> 2022-03-19
user.save!

raw_user = RawUser.find(user.id)
raw_user.name #=> "Joe"
raw_user.expired_at #=> 2022-03-19

another_raw_user = RawUser.create!
another_user = User.find(another_raw_user.id)

another_user.name #=> nil
another_user.expired_at #=> nil

By default, Store Attribute returns the default value even when the record is persisted but the attribute name is not present:

ruby
user = User.create!(extra: {})
user.expired_at #=> 2022-03-19

You can disable this behaviour by setting the store_attribute_unset_values_fallback_to_default class option to false in your model:

ruby
class User  nil

You can also configure the global default for this option in an initializer or application configuration:

ruby
# config/initializers/store_attribute.rb
# # or
# config/application.rb
StoreAttribute.store_attribute_unset_values_fallback_to_default = false

Contributing

Bug reports and pull requests are welcome on GitHub at https://github.com/palkan/store_attribute.

License

The gem is available as open source under the terms of the MIT License.

Issues· 3 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

Rubyactiverecordhacktoberfeststore-accessors

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月17日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言