Create sets of attributes

kostyantyn edited this page Sep 12, 2012 · 4 revisions

What is hydra set?

Hydra Set acts as group for hydra attributes or in other words, hydra attributes can be grouped by hydra sets. Hydra Set can be assigned to entity so each entity can have its own unique set of attributes. If entity hasn't hydra set, it responds to all hydra attributes which were created for its class.

How it works?

Create title, price, total and color attributes.

title = Product.hydra_attributes.create(name: 'title', backend_type: 'string')
price = Product.hydra_attributes.create(name: 'price', backend_type: 'float')
total = Product.hydra_attributes.create(name: 'total', backend_type: 'integer')
color = Product.hydra_attributes.create(name: 'color', backend_type: 'string')

Create Default and General attribute sets and assign attributes to them.

default = Product.hydra_sets.create(name: 'Default')
general = Product.hydra_sets.create(name: 'General')

default.hydra_attributes = [title, price, total]
general.hydra_attributes = [title, price, color]

If hydra_set_id is passed to entity, it will respond to attributes which are in hydra set.
#<Product id: nil, hydra_set_id: 1, created_at: nil, updated_at: nil, price: nil, title: nil, total: nil>
#<Product id: nil, hydra_set_id: 2, created_at: nil, updated_at: nil, price: nil, title: nil, color: nil>

If hydra_set_id isn't passed, entity will respond to all attributes.
#<Product id: nil, hydra_set_id: nil, created_at: nil, updated_at: nil, color: nil, title: nil, price: nil, total: nil> 

How does hydra set filter attributes?

When the attribute which doesn't exist in hydra set is assigned, HydraAttribute::MissingAttributeInHydraSetError will be raised.

product =
product.assign_attributes(color: 'red')
# ActiveRecord::UnknownAttributeError: unknown attribute: color

product.color = 'red'
# HydraAttribute::MissingAttributeInHydraSetError: Attribute "color" does not exist in hydra set "Default"

Notice: assign_attributes method throws ActiveRecord::UnknownAttributeError because product doesn't respond to color=.

When attributes are assigned and hydra set is set, all attributes that do not exist in hydra set will be removed and exception will not be raised. 'red', title: 'toy') do |product|
  product.hydra_set_id =
#<Product id: nil, hydra_set_id: 1, created_at: nil, updated_at: nil, price: nil, title: "toy", total: nil>