main
 1# frozen_string_literal: true
 2
 3module Scim
 4  module Kit
 5    module V2
 6      # Represents a SCIM Resource
 7      class Resource
 8        include ::ActiveModel::Validations
 9        include Attributable
10        include Templatable
11
12        attr_reader :meta
13        attr_reader :schemas
14        attr_reader :raw_attributes
15
16        validate :schema_validations
17
18        def initialize(schemas:, location: nil, attributes: {})
19          @meta = Meta.new(schemas[0]&.name, location)
20          @meta.disable_timestamps
21          @schemas = schemas
22          @raw_attributes = attributes
23          schemas.each { |x| define_attributes_for(self, x.attributes) }
24          attribute(AttributeType.new(name: :id), self)
25          attribute(AttributeType.new(name: :external_id), self)
26          assign_attributes(attributes)
27          yield self if block_given?
28        end
29
30        # Returns the current mode.
31        #
32        # @param type [Symbol] The mode `:server` or `:client`.
33        # @return [Boolean] Returns true if the resource matches the # type of mode
34        def mode?(type)
35          case type.to_sym
36          when :server
37            meta&.location
38          else
39            meta&.location.nil?
40          end
41        end
42
43        # Returns the name of the jbuilder template file.
44        # @return [String] the name of the jbuilder template.
45        def template_name
46          'resource.json.jbuilder'
47        end
48
49        private
50
51        def schema_validations
52          schemas.each do |schema|
53            schema.attributes.each do |type|
54              validate_attribute(type)
55            end
56          end
57        end
58
59        def validate_attribute(type)
60          attribute = attribute_for(type.name)
61          errors.merge!(attribute.errors) unless attribute.valid?
62        end
63      end
64    end
65  end
66end