Sha256: 84a42f4425c97f81b59c0f9694736c468d12e808793b82c26dfffd34c7b5845c

Contents?: true

Size: 1.49 KB

Versions: 10

Compression:

Stored size: 1.49 KB

Contents

module Para
  module AttributeField
    class RelationField < AttributeField::Base
      private

      def reflection
        @reflection ||= model.reflect_on_association(name)
      end

      def foreign_key
        @foreign_key ||= reflection && case reflection.macro
        when :belongs_to then reflection.foreign_key
        when :has_one then :"#{ reflection.name }_id"
        when :has_many then :"#{ reflection.name.to_s.singularize }_ids"
        end
      end

      def resource_name(resource)
        Para.config.resource_name_methods.each do |method|
          return resource.send(method) if resource.respond_to?(method)
        end

        model_name = resource.class.model_name.human
        "#{ model_name } - #{ resource.id }"
      end

      # Takes an array of ids and a block. Check for each id if model exists
      # and create one if not. E.g: [12, "foo"] will try to create a model with
      # 'foo'
      def on_the_fly_creation ids, &block
        Array.wrap(ids).each do |id|
          if !reflection.klass.exists?(id: id)
            resource = reflection.klass.new

            Para.config.resource_name_methods.each do |method_name|
              setter_name = :"#{ method_name }="

              if resource.respond_to?(setter_name)
                resource.send(setter_name, id)

                if resource.save
                  block.call(resource, id)
                  break
                end
              end
            end
          end
        end
      end
    end
  end
end

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
para-0.6.9 lib/para/attribute_field/relation.rb
para-0.6.8 lib/para/attribute_field/relation.rb
para-0.6.7 lib/para/attribute_field/relation.rb
para-0.6.3 lib/para/attribute_field/relation.rb
para-0.6.2 lib/para/attribute_field/relation.rb
para-0.5.4 lib/para/attribute_field/relation.rb
para-0.5.3 lib/para/attribute_field/relation.rb
para-0.5.1 lib/para/attribute_field/relation.rb
para-0.5.0 lib/para/attribute_field/relation.rb
para-0.4.0 lib/para/attribute_field/relation.rb