Sha256: 15f2335a54fe2e70875864220aa64cab08815ab2845a4bb1b0dccfcb50e87697

Contents?: true

Size: 1.1 KB

Versions: 9

Compression:

Stored size: 1.1 KB

Contents

# frozen_string_literal: true

require 'active_support/concern'

module AppStoreDevApi
  module Object
    module Attributes
      extend ActiveSupport::Concern

      class_methods do
        def attributes(&block)
          self::Attributes.class_eval(&block)
        end
      end

      included do
        attr_reader :attributes

        klass = Class.new do |attributes|
          include Object::Properties

          attributes.send(:define_method, :initialize) do |**kwargs|
            self.class.properties.each do |name, options|
              raise ArgumentError, "#{name} required" if options[:required] && !kwargs[name]

              value = kwargs.fetch(name, options[:default])

              instance_variable_set("@#{name}", value)
            end
          end

          def to_h
            {}.tap do |hash|
              self.class.properties.each_key do |name|
                value = instance_variable_get("@#{name}")

                hash[name] = value unless value.nil?
              end
            end
          end
        end

        const_set('Attributes', klass)
      end
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
app_store_dev_api-0.1.9 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.8 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.7 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.6 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.4 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.3 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.2 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.1 lib/app_store_dev_api/object/attributes.rb
app_store_dev_api-0.1.0 lib/app_store_dev_api/object/attributes.rb