Sha256: fee46de7cbbf4c36562b168bba15f6361b672bd45930eb5e8d852f2da710fa9d

Contents?: true

Size: 1.56 KB

Versions: 1

Compression:

Stored size: 1.56 KB

Contents

module JSONAPIonify::Api
  module Resource::Definitions::Attributes

    def self.extended(klass)
      klass.class_eval do
        extend JSONAPIonify::InheritedAttributes
        extend JSONAPIonify::Types
        inherited_array_attribute :attributes
        delegate :attributes, to: :class

        context(:fields, readonly: true) do |context|
          should_error = false
          fields       = (context.request.params['fields'] || {}).each_with_object(self.class.api.fields) do |(type, fields), field_map|
            type_sym            = type.to_sym
            field_map[type_sym] =
              fields.to_s.split(',').map(&:to_sym).each_with_object([]) do |field, field_list|
                attribute = self.class.api.resource(type_sym).attributes.find do |attribute|
                  attribute.read? && attribute.name == field
                end
                attribute ? field_list << attribute.name : error(:field_not_permitted, type, field) && (should_error = true)
              end
          end
          raise error_exception if should_error
          fields
        end
      end
    end

    def id(sym)
      define_singleton_method :id_attribute do
        sym
      end
    end

    def attribute(name, type, description = '', **options)
      Attribute.new(name, type, description, **options).tap do |new_attribute|
        attributes.delete(new_attribute)
        attributes << new_attribute
      end
    end

    def fields
      attributes.select(&:read?).map(&:name)
    end

    def field_valid?(name)
      fields.include? name.to_sym
    end

  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
jsonapionify-0.0.1.pre lib/jsonapionify/api/resource/definitions/attributes.rb