module Statham::Document::ClassMethods
Public Instance Methods
Internal: Define required getter/setter methods for child attributes in JSON and set up ActiveRecord serialization with the set.
set - AttributeSet
object to apply.
Returns attributes in AttributeSet
object.
# File lib/statham/document.rb, line 92 def apply_statham_attribute_set(attribute_set, implicit_serialization = false) serialize attribute_set.name, Statham::Serializer.new(attribute_set, implicit_serialization) attribute_set.attributes.each do |name, attribute| define_method(name) do parent_attribute = send(attribute_set.name) if parent_attribute.has_key?(name) attribute.deserialize(parent_attribute[name]) else attribute.default end end define_method("#{name}=") do |value| send(attribute_set.name)[name] = attribute.serialize(value) end end end
Internal: Tests if column with specified name has json type.
column_name - Name of the column.
Returns true if type is json, false otherwise.
# File lib/statham/document.rb, line 43 def json_type_column?(column_name) begin columns.detect do |column| column.name == column_name.to_s end.type.in?([:json, :jsonb]) rescue # Failed to fetch columns: Database have not been loaded nor migrated. end end
Internal: Find AttributeSets defined in parent classes and return the nearest AttributeSet
if it exists.
column_name - Name of the column to find.
Returns AttributeSet
with parent set.
# File lib/statham/document.rb, line 74 def parent_statham_attribute_set_for(column_name) parent = statham_attribute_sets_collection.inject({}) do |parents, (klass, attribute_sets)| if klass > self && parent_attribute_set = attribute_sets[column_name] parents.merge(klass => parent_attribute_set) else parents end end.sort.first parent && parent.last end
Public: Initializes and creates JSON attribute with specified name containing defined child attributes.
column_name - Symbol object containing name of parent JSON column. block - Required block containing definitions for child
attributes.
Returns Statham::AttributeSet
object for newly defined parent JSON.
# File lib/statham/document.rb, line 29 def statham(column_name, &block) parent = parent_statham_attribute_set_for(column_name) attribute_set = statham_attribute_sets[column_name] ||= Statham::AttributeSet.new(name: column_name, parent: parent) yield attribute_set if block_given? apply_statham_attribute_set(attribute_set, json_type_column?(column_name)) end
Internal: Collection of JSON attributes used as parent attributes for a class.
Returns hash object for the collection.
# File lib/statham/document.rb, line 57 def statham_attribute_sets statham_attribute_sets_collection[self] ||= {} end
Internal: Collection of statham_attribute_sets
for related classes.
Returns hash object for the collection.
# File lib/statham/document.rb, line 64 def statham_attribute_sets_collection @@attribute_sets_collection ||= {} end