Class: Pakyow::Presenter::Attributes::Hash

Inherits:
Attribute
  • Object
show all
Extended by:
Forwardable, Support::SafeStringHelpers
Includes:
Support::SafeStringHelpers
Defined in:
lib/pakyow/presenter/attributes/hash.rb

Overview

Wraps the value for a hash-type view attribute (e.g. style).

Behaves just like a normal Hash.

Constant Summary collapse

VALUE_SEPARATOR =
":".freeze
PAIR_SEPARATOR =
";".freeze
WRITE_VALUE_SEPARATOR =
": ".freeze
WRITE_PAIR_SEPARATOR =
"; ".freeze

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Attribute

#==, #initialize, #initialize_copy

Constructor Details

This class inherits a constructor from Pakyow::Presenter::Attributes::Attribute

Class Method Details

.parse(value) ⇒ Object



72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/pakyow/presenter/attributes/hash.rb', line 72

def parse(value)
  if value.is_a?(::Hash)
    new(::Hash[value.map { |k, v| [ensure_html_safety(k), ensure_html_safety(v.to_s)]}])
  elsif value.respond_to?(:to_s)
    new(value.to_s.split(PAIR_SEPARATOR).each_with_object({}) { |style, attributes|
      key, value = style.split(VALUE_SEPARATOR)
      next unless key && value
      attributes[ensure_html_safety(key.strip)] = ensure_html_safety(value.strip)
    })
  else
    raise ArgumentError.new("expected value to be a Hash or String")
  end
end

Instance Method Details

#[](key) ⇒ Object



36
37
38
# File 'lib/pakyow/presenter/attributes/hash.rb', line 36

def [](key)
  @value[key.to_s]
end

#[]=(key, value) ⇒ Object



40
41
42
# File 'lib/pakyow/presenter/attributes/hash.rb', line 40

def []=(key, value)
  @value[ensure_html_safety(key)] = ensure_html_safety(value)
end

#delete(key) ⇒ Object



44
45
46
# File 'lib/pakyow/presenter/attributes/hash.rb', line 44

def delete(key)
  @value.delete(key.to_s)
end

#include?(key) ⇒ Boolean

Returns:



28
29
30
# File 'lib/pakyow/presenter/attributes/hash.rb', line 28

def include?(key)
  @value.include?(key.to_s)
end

#to_sObject



48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# File 'lib/pakyow/presenter/attributes/hash.rb', line 48

def to_s
  string = ::String.new
  first = true
  @value.each do |key, value|
    unless first
      string << WRITE_PAIR_SEPARATOR
    end

    string << key
    string << WRITE_VALUE_SEPARATOR
    string << value
    first = false
  end

  unless string.empty?
    string = string + PAIR_SEPARATOR
  end

  string
end

#value?(value) ⇒ Boolean

Returns:



32
33
34
# File 'lib/pakyow/presenter/attributes/hash.rb', line 32

def value?(value)
  @value.value?(value.to_s)
end