Sha256: 22610f8c717ea4ccec57fb1b1d1a127beab9f6a81717cadb7a8c136becb539b4

Contents?: true

Size: 1.25 KB

Versions: 6

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Qismo
  #
  # Base object of Qismo object
  #
  class Base
    #
    # Transform object to hash
    #
    # @return [Hash]
    #
    def as_json
      hash = {}
      instance_variables.each { |var| hash[var.to_s.delete("@")] = instance_variable_get(var) }

      hash
    end

    # @return [Array<Object>]
    def self.descendants
      ObjectSpace.each_object(Class).select { |klass| klass < self }
    end

    private

    #
    # Initialize object
    #
    # @param attrs [Hash] Attributes of object
    #
    def initialize(attrs = {})
      attrs.each do |key, value|
        initiate_object(key, value)
      end
    end

    #
    # Dynamically tranform hash to class attributes
    #
    # @param key [String,Symbol]
    # @param value [String,Integer,TrueClass,FalseClass,Hash,Array]
    #
    #
    def initiate_object(key, value)
      if value.is_a?(TrueClass) || value.is_a?(FalseClass)
        key_s = key.to_s
        method_name = key_s.start_with?("is_") ? key_s.gsub("is_", "") : key_s
        method_name += "?"

        self.class.define_method(method_name) do
          value
        end
      end

      instance_variable_set("@#{key}", value)
      self.class.class_eval { attr_reader(key.to_sym) }
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
qismo-0.1.8 lib/qismo/models/base.rb
qismo-0.1.5 lib/qismo/models/base.rb
qismo-0.1.4 lib/qismo/models/base.rb
qismo-0.1.2 lib/qismo/models/base.rb
qismo-0.1.1 lib/qismo/models/base.rb
qismo-0.1.0 lib/qismo/models/base.rb