module Netfira::WebConnect::Model::Record::Materialization

Public Instance Methods

materialize(name, has_languages, props) click to toggle source
# File lib/netfira/web_connect/model/record/materialization.rb, line 7
def materialize(name, has_languages, props)

  # Get a reference to the record class, creating it if it doesn't exist
  klass = begin
    Models.const_get name
  rescue NameError
    Models.const_set name, Class.new(props.file ? FileRecord : self)
  end

  # Give the model access to properties from the `tables` table
  klass.instance_variable_set :@table_props, props

  # Add a reference to the record's shop
  shop_relation = name.underscore.pluralize.to_sym
  klass.belongs_to :shop,
                   class_name: 'Netfira::WebConnect::Models::Shop',
                   inverse_of: shop_relation

  # Add a has-many to Shop so we can do Shop.first.products etc
  Models::Shop.has_many shop_relation, inverse_of: :shop

  # Set up access to localised fields
  if has_languages
    Model::Record::Translation.materialize klass
    klass.include Model::Record::Translations
    translated_attributes = klass::Translation.attribute_names.reject do |attribute|
      (%w[id language] << "#{klass.single_name}_id").include? attribute
    end
    translated_attributes.each do |attribute|
      klass.__send__ :define_method, :"#{attribute}" do
        self.get_translated_string attribute.to_sym
      end
      klass.__send__ :define_method, :"#{attribute}=" do |value|
        self.set_translated_string attribute.to_sym, value
      end
    end
  end

  # Set up tree behaviour (parent/child relations)
  klass.include Model::Record::Tree if klass.tree?

  # Set up writable behaviour
  klass.include Model::Record::Writable if klass.writable?

  # Set up sendable behaviour
  klass.include Model::Record::Sendable if klass.sendable?

  # Set up paranoia (soft deletion)
  if Netfira::WebConnect.paranoia?
    klass.acts_as_paranoid
  else
    def klass.with_deleted; self end
  end

  # Set up file record behaviour
  if klass.has_file?
    klass.has_attached_file :attachment, Netfira::WebConnect.file_store
    klass.do_not_validate_attachment_file_type :attachment
  end

end