Sha256: 4b92e3767311562539938fd55c2462612919ef1f1857c3d060a23fa31ccff77d

Contents?: true

Size: 1000 Bytes

Versions: 2

Compression:

Stored size: 1000 Bytes

Contents

# frozen_string_literal: true

require 'active_support/inflector'

module Bouncie
  # Abstract base class for objects returned from API requests. Parses dates, converts keys to underscore.
  class Entity
    def initialize(data)
      @data = data.transform_keys { |k| k.to_s.underscore.to_sym }
      massage_data
    end

    def method_missing(method_name, *args, &block)
      if @data.key?(method_name)
        @data[method_name]
      else
        super
      end
    end

    def respond_to_missing?(method_name, _include_private = false)
      @data.key?(method_name)
    end

    private

    def massage_data
      @data.each do |key, val|
        if val.is_a?(Hash)
          @data[key] = Bouncie::Entity.new(val)
        elsif val.is_a?(Array)
          @data[key] = val.map { |v| Bouncie::Entity.new(v) }
        elsif val.is_a?(String) && %w[_updated _time timestamp].any? { |v| key.to_s.end_with?(v) }
          @data[key] = DateTime.parse(val)
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
bouncie-0.6.0 lib/bouncie/entity.rb
bouncie-0.4.0 lib/bouncie/entity.rb