Skip to content

kaspernj/acts_as_customized_attributes

Repository files navigation

Code Climate Test Coverage Build Status

ActsAsCustomizedAttributes

Add custom attributes to your models, which doesn't have predefined names but can be created runtime, and still be able to do queries on that data.

Install

Bundle

Add this to your Gemfile and bundle:

gem 'acts_as_customized_attributes'

Modify model

class SomeModel
  acts_as_customized_attributes
end

Create a migration

This creates the tables "some_model_data_keys" and "some_model_data", where the custom attributes will be stored.

class AddCustomizedAttributesForSomeModel < ActiveRecord::Migration
  def up
    SomeModel.create_customized_attributes!
  end

  def down
    SomeModel.drop_customized_attributes!
  end
end

Usage

Set customized attributes for a model.

some_model.update_customized_attributes(my_custom_attribute: 5)

Get all custom attributes for a model.

some_model.customized_attributes #=> {:my_custom_attribute => 5}

Queries

model.customized_attribute("name_of_key") #=> "some_value"

Query keys.

SomeModelDataKey.where("name LIKE '%facebook%'")

Query data

SomeModelData.where("resource_id > 5")

Optimize inserts with transactions for inserts / updates.

ActiveRecordTransactioner.new do |trans|
  models.each do |model|
    model.update_customized_attributes_with_args(data: {my_custom_attribute: 5}, transactioner: trans)
  end
end

License

This project uses MIT-LICENSE.

About

A Gem for custom data attributes in ActiveRecord.

Resources

License

Stars

Watchers

Forks

Packages

No packages published