Sha256: d4745e98ec742aeb91693598c94e43b7632edd53312b19e7e706edf4f76a7844

Contents?: true

Size: 1.31 KB

Versions: 5

Compression:

Stored size: 1.31 KB

Contents

# frozen_string_literal: true

module Truelayer
  class BaseModel
    class << self
      def attributes(*attributes)
        @attributes ||= []

        return @attributes unless attributes

        attr_accessor(*attributes)

        @attributes += attributes
      end

      def attribute_aliases(aliases = nil)
        @attribute_aliases ||= {}

        return @attribute_aliases unless aliases

        @attribute_aliases.merge!(aliases)
      end

      # Sets all the instance variables by reading the JSON from API
      def build(json: {})
        new.tap do |record|
          attributes.each do |attr|
            key = attribute_aliases.key?(attr) ? attribute_aliases[attr] : attr
            record.public_send("#{attr}=", json[key])
          end
        end
      end
    end

    def initialize(attributes = {})
      attributes.each do |attr, value|
        public_send("#{attr}=", value)
      end
    end

    def as_json
      self.class.attributes.each_with_object({}) do |attr, hash|
        value = public_send(attr)

        value = value.as_json if value.respond_to?(:as_json)
        if value.is_a?(Array)
          value = value.map { |v| v.respond_to?(:as_json) ? v.as_json : v }
        end
        value = value.iso8601 if value.respond_to?(:iso8601)

        hash[attr] = value
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
truelayer-0.1.4 lib/truelayer/base_model.rb
truelayer-0.1.3 lib/truelayer/base_model.rb
truelayer-0.1.2 lib/truelayer/base_model.rb
truelayer-0.1.1 lib/truelayer/base_model.rb
truelayer-0.1.0 lib/truelayer/base_model.rb