Sha256: 63d871f009435a4e80a22b589da034a00eb9fca7684100d8af611d37cbc588c9

Contents?: true

Size: 1.5 KB

Versions: 1

Compression:

Stored size: 1.5 KB

Contents

module Encore
  module Persister
    module LinksParser
      extend ActiveSupport::Concern

      def parse_links(args)
        links = args.delete(:links) || []

        links.each do |link, value|
          reflections = @model.try(:_reflections) || @model.reflections
          reflection = reflections[link.to_sym]
          key = fetch_key(reflection)
          value = fetch_value(value, reflection)

          args.merge!(key => value) if key
        end

        args
      end

    private

      # `belongs_to` => 'user' become 'user_id'
      def link_belongs_to(reflection)
        reflection.foreign_key.to_sym
      end

      # `has_many` => 'users' become 'user_ids'
      def link_has_many(reflection)
        "#{reflection.name.to_s.singularize}_ids".to_sym
      end

      # `has_one` => 'user' stay 'user'
      def link_has_one(reflection)
        reflection.name
      end

      # Convert reflection with the right ActiveRecord key for insert/update.
      def fetch_key(reflection)
        case reflection.macro
          when :belongs_to then link_belongs_to(reflection)
          when :has_many then link_has_many(reflection)
          when :has_one then link_has_one(reflection)
        end
      end

      # Value for `has_one` must be an activerecord instance.
      # Other reflection macro types stay the same.
      def fetch_value(value, reflection)
        if reflection.macro == :has_one
          reflection.klass.find(value)
        else
          value
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
encore-0.2.2 lib/encore/persister/links_parser.rb