Class: HttpObjects::Hash

Inherits:
Hash
  • Object
show all
Extended by:
HttpObjects::Headers::Attributes
Defined in:
lib/http_objects/hash.rb

Constant Summary collapse

MethodCreator =

Public: Block that creates method based on attribute name.

Proc.new do |name, header|
  attr_name = name.downcase.gsub("-", "_")
  self.class_eval(%{
    def #{attr_name}                          # def content_type
      self.fetch("#{name}", nil)       #   self.fetch("Content-Type", nil)
    end                                       # end
    def #{attr_name}!                         # def content_type!
      self.#{attr_name}.raw if #{attr_name}?  #   self.content_type.raw if content_type?
    end                                       # end
    def #{attr_name}?                         # def content_type?
      !!self.fetch("#{name}", nil)     #   !!self.fetch("Content-Type", nil)
    end                                       # end
  })
end

Class Method Summary collapse

Instance Method Summary collapse

Methods included from HttpObjects::Headers::Attributes

attributes, register_attribute

Constructor Details

#initialize(hash = nil) ⇒ Hash

Returns a new instance of Hash.



31
32
33
34
# File 'lib/http_objects/hash.rb', line 31

def initialize(hash = nil)
  super()
  hash.each { |(key, value)| self[key] = value } unless hash.nil?
end

Class Method Details

.add_attribute(attr_class) ⇒ Object

Public: Register attribute class with MethodCreator block.



23
24
25
# File 'lib/http_objects/hash.rb', line 23

def self.add_attribute(attr_class)
  register_attribute(attr_class.header_name, attr_class, &MethodCreator)
end

.new(hash = nil) ⇒ Object



27
28
29
# File 'lib/http_objects/hash.rb', line 27

def self.new(hash = nil)
  hash.kind_of?(HttpObjects::Hash) ? hash : super(hash)
end

Instance Method Details

#[]=(key, value) ⇒ Object Also known as: store

Public: Associates key with value. If key is a valid HTTP Header name, like “Content-Type”, it parses as HTTP Object.

key - key or HTTP Header name. value - object. If key is HTTP Header name, value should be a String.



41
42
43
44
45
46
# File 'lib/http_objects/hash.rb', line 41

def []=(key, value)
  if (header_class = self.class.attributes[key])
    value = header_class.parse(value)
  end
  super(key, value)
end