Sha256: 0982dce2ea945d70906e2652cbd50a1429a9111de003b691290cb75dfa47474d

Contents?: true

Size: 1.22 KB

Versions: 9

Compression:

Stored size: 1.22 KB

Contents

require "part"

module Parted
  def self.included(klass)
    klass.embeds_many :parts
    klass.accepts_nested_attributes_for :parts, allow_destroy: true,
      reject_if: proc { |attrs| attrs["title"].blank? and attrs["body"].blank? }
    klass.after_validation :merge_embedded_parts_errors
  end

  def build_clone(target_class=nil)
    new_edition = super

    # If the new edition is of the same type or another type that has parts,
    # copy over the parts from this edition
    if target_class.nil? or target_class.include? Parted
      new_edition.parts = self.parts.map {|p| p.dup }
    end

    new_edition
  end

  def order_parts
    ordered_parts = parts.sort_by { |p| p.order ? p.order : 99999 }
    ordered_parts.each_with_index do |obj, i|
      obj.order = i + 1
    end
  end

  def whole_body
    self.parts.in_order.map { |i| %(\# #{i.title}\n\n#{i.body}) }.join("\n\n")
  end

  private

  def merge_embedded_parts_errors
    return if parts.empty?

    if errors.delete(:parts) == ["is invalid"]
      parts_errors = parts.inject({}) do |result, part|
        result["#{part._id}:#{part.order}"] = part.errors.messages if part.errors.present?
        result
      end
      errors.add(:parts, parts_errors)
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
govuk_content_models-41.1.0 app/models/parted.rb
govuk_content_models-41.0.0 app/models/parted.rb
govuk_content_models-40.0.0 app/models/parted.rb
govuk_content_models-39.0.0 app/models/parted.rb
govuk_content_models-38.0.0 app/models/parted.rb
govuk_content_models-37.0.0 app/models/parted.rb
govuk_content_models-36.0.0 app/models/parted.rb
govuk_content_models-35.0.1 app/models/parted.rb
govuk_content_models-35.0.0 app/models/parted.rb