Sha256: 817fcd36d4f571b9b4ce81b06845c439b19e10fa812564af7157a0bd1075bb78

Contents?: true

Size: 1.48 KB

Versions: 19

Compression:

Stored size: 1.48 KB

Contents

module CustomFields

  module Types

    module BelongsTo

      module Field

        extend ActiveSupport::Concern

        included do

          def belongs_to_to_recipe
            { 'class_name' => self.class_name }
          end

          def belongs_to_is_relationship?
            self.type == 'belongs_to'
          end

        end

      end

      module Target

        extend ActiveSupport::Concern

        module ClassMethods

          # Adds a belongs_to relationship between 2 models
          #
          # @param [ Class ] klass The class to modify
          # @param [ Hash ] rule It contains the name of the field and if it is required or not
          #
          def apply_belongs_to_custom_field(klass, rule)
            # puts "#{klass.inspect}.belongs_to #{rule['name'].inspect}, class_name: #{rule['class_name'].inspect}" # DEBUG

            position_name = "position_in_#{rule['name'].underscore}"

            # puts "#{klass.inspect}.field :#{position_name}" # DEBUG

            klass.field position_name, type: ::Integer, default: 0

            klass.belongs_to rule['name'].to_sym, class_name: rule['class_name']

            if rule['required']
              klass.validates_presence_of rule['name'].to_sym
            end

            klass.before_create do |object|
              position = (object.class.max(position_name.to_sym) || 0) + 1
              object.send(:"#{position_name}=", position)
            end
          end

        end

      end

    end

  end

end

Version data entries

19 entries across 19 versions & 2 rubygems

Version Path
custom_fields-2.4.0.rc6 lib/custom_fields/types/belongs_to.rb
custom_fields-2.3.4 lib/custom_fields/types/belongs_to.rb
custom_fields-2.4.0.rc5 lib/custom_fields/types/belongs_to.rb
custom_fields-2.3.3 lib/custom_fields/types/belongs_to.rb
custom_fields-2.4.0.rc4 lib/custom_fields/types/belongs_to.rb
custom_fields-2.4.0.rc3 lib/custom_fields/types/belongs_to.rb
custom_fields-2.4.0.rc2 lib/custom_fields/types/belongs_to.rb
custom_fields-2.3.2 lib/custom_fields/types/belongs_to.rb
custom_fields-2.4.0.rc1 lib/custom_fields/types/belongs_to.rb
gnuside-custom_fields-2.3.2.2 lib/custom_fields/types/belongs_to.rb
gnuside-custom_fields-2.3.2 lib/custom_fields/types/belongs_to.rb
gnuside-custom_fields-2.3.1.1 lib/custom_fields/types/belongs_to.rb
gnuside-custom_fields-2.3.1 lib/custom_fields/types/belongs_to.rb
custom_fields-2.3.1 lib/custom_fields/types/belongs_to.rb
custom_fields-2.3.0 lib/custom_fields/types/belongs_to.rb
custom_fields-2.2.3 lib/custom_fields/types/belongs_to.rb
custom_fields-2.2.2 lib/custom_fields/types/belongs_to.rb
custom_fields-2.2.1 lib/custom_fields/types/belongs_to.rb
custom_fields-2.2.0 lib/custom_fields/types/belongs_to.rb