Sha256: 749239346408d0318bcd543463bf30acc50c26edb9e3665a0c5671e842486a01

Contents?: true

Size: 1.59 KB

Versions: 1

Compression:

Stored size: 1.59 KB

Contents

module JSONAPI
  module Attributes
    def self.included(target)
      target.send(:include, InstanceMethods)
      target.extend ClassMethods
    end

    module InstanceMethods
    end

    module ClassMethods
      attr_accessor :attributes_map
      attr_accessor :to_one_associations
      attr_accessor :to_many_associations

      def attribute(name, options = {}, &block)
        add_attribute(name, options, &block)
      end

      def has_one(name, options = {})
        add_to_one_association(name, options)
      end

      def has_many(name, options = {})
        add_to_many_association(name, options)
      end

      def add_attribute(name, options = {}, &block)
        # Blocks are optional and can override the default attribute discovery. They are just
        # stored here, but evaluated by the Serializer within the instance context.
        @attributes_map ||= {}
        @attributes_map[name] = {
          attr_or_block: block_given? ? block : name,
          options: options,
        }
      end
      private :add_attribute

      def add_to_one_association(name, options = {}, &block)
        @to_one_associations ||= {}
        @to_one_associations[name] = {
          attr_or_block: block_given? ? block : name,
          options: options,
        }
      end
      private :add_to_one_association

      def add_to_many_association(name, options = {}, &block)
        @to_many_associations ||= {}
        @to_many_associations[name] = {
          attr_or_block: block_given? ? block : name,
          options: options,
        }
      end
      private :add_to_many_association
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsonapi-serializers-0.1.0 lib/jsonapi-serializers/attributes.rb