Sha256: 10250dd9dac636e99e08ad0f901aac76c7ca26a90c626999814f17408c701880

Contents?: true

Size: 783 Bytes

Versions: 1

Compression:

Stored size: 783 Bytes

Contents

class SweeperAPI::Resources::Base
  def self.dynamic_accessor(*attrs)
    attrs.each do |attr|
      class_eval do
        define_method(attr) { _attrs[attr] }
        define_method("#{attr}?") { !!_attrs[attr] } # rubocop:disable Style/DoubleNegation
        define_method("#{attr}=") { |value| _attrs[attr] = value }
      end
    end
  end

  def initialize(response)
    response.each { |key, value| _attrs[key] = parse_attribute(value) }

    metaclass = (class << self; self; end)
    metaclass.send(:dynamic_accessor, *_attrs.keys)
  end

  private

  def _attrs
    @_attrs ||= {}
  end

  def parse_attribute(attr)
    case attr
    when Hash then SweeperAPI::Resources::Base.new(attr)
    when Array then attr.map(&method(:parse_attribute))
    else attr
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
sweeper_api-0.0.1 lib/sweeper_api/resources/base.rb