项目作者: fnando

项目描述 :
Add default value for ActiveRecord attributes
高级语言: Ruby
项目地址: git://github.com/fnando/defaults.git
创建时间: 2008-07-21T01:24:10Z
项目社区:https://github.com/fnando/defaults

开源协议:

下载


Defaults

Tests
Gem
Gem

Instalation

Add this line to your application’s Gemfile:

  1. gem "defaults"

And then execute:

  1. $ bundle

Or install it yourself as:

  1. $ gem install defaults

Usage

Here are the rules:

  1. Assigned attributes have precedence over default values
  2. Default values have precedence over database defaults.

Add the method call defaults to your model.

  1. class Page < ActiveRecord::Base
  2. defaults title: "New page",
  3. body: "Put your text here"
  4. end

Attributes will be set only if it’s a new record and the attribute is blank.

Retrieve the default attribute with the default_for instance method:

  1. @page.default_for(:title)

You can pass callables (any objects that respond to .call() or
.call(record)) as attribute:

  1. class Expiration
  2. def self.call
  3. Time.now
  4. end
  5. end
  6. class Checksum
  7. def self.call(user)
  8. Digest::SHA1.hexdigest(user.name.to_s, user.email.to_s)
  9. end
  10. end
  11. class User < ApplicationRecord
  12. defaults checksum: Checksum,
  13. expires_at: -> { Time.now }
  14. end

You can override the default attributes as follow:

  1. Page.default_values = {
  2. title: "Here's your new page",
  3. body: "Write your page text"
  4. }

Maintainer

Contributors

Contributing

For more details about how to contribute, please read
https://github.com/fnando/defaults/blob/main/CONTRIBUTING.md.

License

The gem is available as open source under the terms of the
MIT License. A copy of the license can be
found at https://github.com/fnando/defaults/blob/main/LICENSE.md.

Code of Conduct

Everyone interacting in the defaults project’s codebases, issue trackers, chat
rooms and mailing lists is expected to follow the
code of conduct.