module Composable::Core::ComposableDSL

Public Class Methods

new(options = {}) click to toggle source

In order to prevent attribute values passed in at initialize from being overridden by composable_record values, composable_record mapping methods have to be synced first.

Calls superclass method
# File lib/composable/core/composable_dsl.rb, line 36
def initialize(options = {})
  composable_keys.each do |attribute|
    value = options.delete(attribute) || options.delete(attribute.to_s)
    send("#{attribute}=", value) if value
  end

  super
end

Public Instance Methods

composables() click to toggle source
# File lib/composable/core/composable_dsl.rb, line 45
def composables
  self.class.composables
end
save_composables() { || ... } click to toggle source
# File lib/composable/core/composable_dsl.rb, line 49
def save_composables
  multi_db_transaction do
    sync_composable_records
    save_composable_records

    yield if block_given?
  end
end

Private Instance Methods

composable_keys() click to toggle source
# File lib/composable/core/composable_dsl.rb, line 89
def composable_keys
  @composable_keys ||= composables.keys.freeze
end
composable_record_for(attribute) click to toggle source
# File lib/composable/core/composable_dsl.rb, line 93
def composable_record_for(attribute)
  send(attribute) or
    raise ArgumentError, "required composable argument: #{attribute}"
end
multi_db_transaction(attribute: composable_keys.first) { || ... } click to toggle source

Ensures ‘save!` queries are wrapped within multiple db transactions. It might be the case that our service is working with several composable objects that are gonna be saved into diffent databases, if there is an error, all transactions are gonna be rollback regardless of the DB.

# File lib/composable/core/composable_dsl.rb, line 78
def multi_db_transaction(attribute: composable_keys.first, &block)
  return yield if attribute.nil?

  index = composable_keys.index(attribute)
  record = composable_record_for(attribute)

  multi_db_transaction(attribute: composable_keys[index + 1]) do
    record.respond_to?(:transaction) ? record.transaction(&block) : yield
  end
end
save_composable_records() click to toggle source
# File lib/composable/core/composable_dsl.rb, line 67
def save_composable_records
  composables.each do |attribute, composable|
    record = composable_record_for(attribute)
    record.save! if composable.valid?(self, record)
  end
end
sync_composable_records() click to toggle source
# File lib/composable/core/composable_dsl.rb, line 60
def sync_composable_records
  composables.each do |attribute, composable|
    record = composable_record_for(attribute)
    composable.sync_attributes(self, record) if composable.valid?(self, record)
  end
end