Sha256: a3a1aa55d2e0da71caaee624143eb3a1333f2ac123bc1369b14bd5c21ab64db4

Contents?: true

Size: 1.54 KB

Versions: 1

Compression:

Stored size: 1.54 KB

Contents

module GifterHub
  class ApiResource
    include Operations::Get
    attr_accessor :id, :opts

    def initialize(id=nil, opts={})
      @id = id
      @opts = opts
      @values = {}
    end

    def self.class_name
      self.name.split('::')[-1]
    end

    def self.resource_url
      if self == ApiResource
        raise NotImplementedError
      end
      "/api#{CGI.escape(class_name.tableize)}"
    end

    def self.get(id, opts={})
      instance = self.new(id, opts)
      instance.refresh
    end

    def resource_url
      "#{self.class.resource_url}/#{CGI.escape(id)}"
    end

    def refresh
      response = request(:get, resource_url, opts)
      initialize_from(response, opts)
    end

    private

    def self.check_id!(id)
      raise TypeError.new('id should be a string') unless id.is_a? String
      id
    end

    def protected_fields
      []
    end

    # Convert hash key value pair to method
    def initialize_from(values, opts={})
      @opts = opts
      added = Set.new(values.keys - @values.keys)
      instance_eval do
        add_accessors(added, values)
      end
      self
    end

    def add_accessors(keys, values)
      f = protected_fields
      metaclass.instance_eval do
        keys.each do |k|
          next if f.include?(k)
          define_method(k) { values[k] }

          if [FalseClass, TrueClass].include?(values[k].class)
            k_bool = :"#{k}?"
            define_method(k_bool) { values[k] }
          end
        end
      end
    end

    def metaclass
      class << self; self; end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
gifter_hub-0.1.2 lib/gifter_hub/api_resource.rb