Sha256: a3269cefc1931cbd8c2f9c0abe112cad8fcd4ebdc957a3cbca06a96a21a5919d

Contents?: true

Size: 1.36 KB

Versions: 2

Compression:

Stored size: 1.36 KB

Contents

require 'active_model'
require 'tzinfo'
require 'validate_url'
require 'validate_email'
require 'attr_required'
require 'attr_optional'

module OpenIDConnect
  class ResponseObject
    include ActiveModel::Validations, AttrRequired, AttrOptional

    class ValidationFailed < Exception
      attr_reader :errors

      def initialize(errors)
        super errors.full_messages.to_sentence
        @errors = errors
      end
    end

    def initialize(attributes = {})
      all_attributes.each do |_attr_|
        self.send :"#{_attr_}=", attributes[_attr_]
      end
      attr_missing!
    end

    def all_attributes
      required_attributes + optional_attributes
    end

    def require_at_least_one_attributes
      all_blank = all_attributes.all? do |key|
        self.send(key).blank?
      end
      errors.add :base, 'At least one attribute is required' if all_blank
    end

    def as_json(options = {})
      options ||= {} # options can be nil when to_json is called without options
      validate! unless options[:skip_validation]
      all_attributes.inject({}) do |hash, _attr_|
        hash.merge! _attr_ => self.send(_attr_)
      end.delete_if do |key, value|
        value.nil?
      end
    end

    def validate!
      valid? or raise ValidationFailed.new(errors)
    end
  end
end

Dir[File.dirname(__FILE__) + '/response_object/*.rb'].each do |file|
  require file
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
openid_connect-0.0.25 lib/openid_connect/response_object.rb
openid_connect-0.0.24 lib/openid_connect/response_object.rb