Sha256: bb20e8b6f3b47a3a4f6734c87461de5457b21e0471a122f36f5cade3ddbb11de

Contents?: true

Size: 1.51 KB

Versions: 3

Compression:

Stored size: 1.51 KB

Contents

module Encore
  module Serializer
    module LinksReflectionIncluder
      module Loaded
        def self.reflection_belongs_to(object, reflection)
          object.send(reflection.foreign_key).try(:to_s) if object.respond_to?(reflection.foreign_key)
        end

        def self.reflection_has_one(object, reflection)
          object.send(reflection.name).try(:id).try(:to_s)
        end

        def self.reflection_has_many(object, reflection)
          object.send("#{reflection.name.to_s.singularize}_ids").map(&:to_s) if object.send(reflection.name).loaded?
        end
      end

      module NotLoaded
        def self.reflection_has_many(object, reflection)
          reflection_type = reflection.name.to_s.pluralize

          {
            href: "/#{reflection_type}?#{object.class.name.downcase}_id=#{object.id}",
            type: reflection_type
          }
        end

        def self.reflection_has_one(object, reflection)
          reflection_type = reflection.name.to_s

          {
            href: "/#{object.class.name.downcase.pluralize}/#{object.id}/#{reflection_type}",
            type: reflection_type.pluralize
          }
        end

        def self.reflection_belongs_to(object, reflection)
          reflection_type = reflection.name.to_s.pluralize
          reflection_id = object.send(reflection.foreign_key).try(:to_s)

          {
            href: "/#{reflection_type}/#{reflection_id}",
            id: reflection_id,
            type: reflection_type
          }
        end
      end
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
encore-0.2.1 lib/encore/serializer/links_reflection_includer.rb
encore-0.2 lib/encore/serializer/links_reflection_includer.rb
encore-0.1 lib/encore/serializer/links_reflection_includer.rb