Sha256: a809f8bb2b09a58b433566a9ee15337a0e335869c50bb75b46e99310fe8436cc

Contents?: true

Size: 1.56 KB

Versions: 4

Compression:

Stored size: 1.56 KB

Contents

class Frenetic
  class Resource

    attr_reader :links

    def initialize( attributes = {} )
      if attributes.is_a? Hash
        load attributes.keys, attributes

        @links = {}
      else
        load self.class.schema, attributes

        # Load embedded resources if present
        if attributes.resources
          load attributes.resources.members, attributes.resources
        end

        @links = attributes.links
      end
    end

    # Attempts to retrieve the Resource Schema from the API based on the name
    # of the subclass.
    class << self
      def api_client( client = nil )
        metaclass.instance_eval do
          define_method :api do
            block_given? ? yield : client
          end
        end
      end

      def schema
        if self.respond_to? :api
          class_name = self.to_s.split('::').last.downcase

          api.description.resources.schema.send(class_name).properties
        else
          raise MissingAPIReference,
              "This Resource needs a class accessor defined as " +
              "`.api` that references an instance of Frenetic."
        end
      end

    private

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

  private

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

    def load( keys, attributes )
      keys.each do |key|
        instance_variable_set "@#{key}", attributes[key.to_s]

        metaclass.class_eval do
          define_method key do
            instance_variable_get( "@#{key}")
          end
        end
      end
    end

  end
end

Version data entries

4 entries across 4 versions & 1 rubygems

Version Path
frenetic-0.0.7 lib/frenetic/resource.rb
frenetic-0.0.6 lib/frenetic/resource.rb
frenetic-0.0.5 lib/frenetic/resource.rb
frenetic-0.0.4 lib/frenetic/resource.rb