Class: HttpObjects::Hash
- Inherits:
-
Hash
- Object
- Hash
- HttpObjects::Hash
- Extended by:
- HttpObjects::Headers::Attributes
- Defined in:
- lib/http_objects/hash.rb
Direct Known Subclasses
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
-
.add_attribute(attr_class) ⇒ Object
Public: Register attribute class with MethodCreator block.
- .new(hash = nil) ⇒ Object
Instance Method Summary collapse
- #[](key) ⇒ Object
-
#[]=(key, value) ⇒ Object
(also: #store)
Public: Associates key with value.
-
#initialize(hash = nil) ⇒ Hash
constructor
A new instance of Hash.
- #to_s ⇒ Object
Methods included from HttpObjects::Headers::Attributes
attributes, register_attribute
Constructor Details
#initialize(hash = nil) ⇒ Hash
Returns a new instance of Hash.
32 33 34 35 |
# File 'lib/http_objects/hash.rb', line 32 def initialize(hash = nil) super() hash.each_pair { |(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 26 |
# File 'lib/http_objects/hash.rb', line 23 def self.add_attribute(attr_class) key = normalize_key(attr_class.header_name) register_attribute(key, attr_class, &MethodCreator) end |
.new(hash = nil) ⇒ Object
28 29 30 |
# File 'lib/http_objects/hash.rb', line 28 def self.new(hash = nil) hash.kind_of?(HttpObjects::Hash) ? hash : super(hash) end |
Instance Method Details
#[](key) ⇒ Object
51 52 53 54 55 56 |
# File 'lib/http_objects/hash.rb', line 51 def [](key) key = self.class.normalize_key(key) value = self.fetch(key, nil) value = value.raw if value.respond_to?(:raw) value end |
#[]=(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.
42 43 44 45 46 47 48 |
# File 'lib/http_objects/hash.rb', line 42 def []=(key, value) key = self.class.normalize_key(key) if (header_class = self.class.attributes[key]) value = header_class.parse(value) end super(key, value) end |
#to_s ⇒ Object
58 59 60 61 62 63 |
# File 'lib/http_objects/hash.rb', line 58 def to_s self.keys.inject("") do |out, key| out << ", " unless out.empty? out << "#{key}: #{self[key]}" end end |