ActiveRecord 扩展,它为存储访问器添加类型转换
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.
In your Gemfile:
# 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"You can use store_attribute method to add additional accessors with a type to an existing store on a model.
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:
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 #=> nilBy default, Store Attribute returns the default value even when the record is persisted but the attribute name is not present:
user = User.create!(extra: {})
user.expired_at #=> 2022-03-19You can disable this behaviour by setting the store_attribute_unset_values_fallback_to_default class option to false in your model:
class User nilYou can also configure the global default for this option in an initializer or application configuration:
# config/initializers/store_attribute.rb
# # or
# config/application.rb
StoreAttribute.store_attribute_unset_values_fallback_to_default = falseBug reports and pull requests are welcome on GitHub at https://github.com/palkan/store_attribute.
The gem is available as open source under the terms of the MIT License.
暂无开放 Issues,或尚未同步最近议题。