Gem Version Tests

DynamicFields

DynamicFields allows to add persisted attributes to ActiveRecord models without the need for a migration.

You might want to add a temporary attribute, for monitoring or reporting purposes, or avoid to pollute your domain tables with marketing-related fields.

With DynamicFields, this is as easy as the following:

  class User
    include DynamicFields::ActiveRecord

    has_dynamic_field :subscribe_to_newsletter, field_type: :boolean
  end

  user = User.create(subscribe_to_newsletter: true)
  user.subscribe_to_newsletter # => true

The declared attribute works seamlessly like a traditionnal ActiveRecord attribute. This means you can use features such as validations without any futher work:

class Post
  include DynamicFields::ActiveRecord

  has_dynamic_field :title

  validates :title, presence: true
end

post = Post.new
post.valid? # => false
post.errors.full_messages # => ["Title can't be blank"]

Installation

Add this line to your application's Gemfile:

gem "dynamic_fields"

And then execute:

$ bundle

Or install it yourself as:

$ gem install dynamic_fields

Usage

Persisted attributes are backed by the dynamic_fields_attributes table. After installing the gem run migrations to add the required tables:

rails db:migrate

Once the migrations are done, start adding attributes to model by including the DynamicFields::ActiveRecord module any active record model:

class Post
  include DynamicFields::ActiveRecord
end

And voilĂ ! Your model is ready to declare new dynamic fields. The API is simple:

class Post
  include DynamicFields::ActiveRecord

  # Use `has_dynamic_field` with the field name to declare a new attribute.
  has_dynamic_field :title

  # Default type for a field is :string. Use the `field_type` option to declare another field type
  has_dynamic_field :reading_time, field_type: :integer
  has_dynamic_field :published, field_type: :boolean
end

For now, DynamicFields allow for three field types;

  • String (default)
  • Integer
  • Boolean

The list will likely grow with time, usage and needs.

License

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