Module: Streamlined::Helpers

Included in:
Renderable
Defined in:
lib/streamlined/helpers.rb

Defined Under Namespace

Modules: PipeableProc

Instance Method Summary collapse

Instance Method Details

#attribute_segment(attr, value) ⇒ String

Create an attribute segment for a tag.

Parameters:

  • attr (String)

    the HTML attribute name

  • value (String)

    the attribute value

Returns:

  • (String)


79
80
81
# File 'lib/streamlined/helpers.rb', line 79

def attribute_segment(attr, value)
  "#{attr}=#{value.to_s.encode(xml: :attr)}"
end

#dashed(value) ⇒ String

Covert an underscored value into a dashed string.

Examples:

“foo_bar_baz” => “foo-bar-baz”


Parameters:

  • value (String|Symbol)

Returns:

  • (String)


70
71
72
# File 'lib/streamlined/helpers.rb', line 70

def dashed(value)
  value.to_s.tr("_", "-")
end

#html(callback) ⇒ Object



91
92
93
# File 'lib/streamlined/helpers.rb', line 91

def html(callback)
  callback.html_safe.pipe
end

#html_attributes(options = nil, prefix_space: false, **kwargs) ⇒ String

Create a set of attributes from a hash.

Parameters:

  • options (Hash) (defaults to: nil)

    key-value pairs of HTML attributes (or use keyword arguments)

  • prefix_space (Boolean) (defaults to: false)

    add a starting space if attributes are present, useful in tag builders

Returns:

  • (String)


47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# File 'lib/streamlined/helpers.rb', line 47

def html_attributes(options = nil, prefix_space: false, **kwargs)
  options ||= kwargs
  segments = []
  options.each do |attr, option|
    attr = dashed(attr)
    if option.is_a?(Hash)
      option = option.transform_keys { |key| "#{attr}-#{dashed(key)}" }
      segments << html_attributes(option)
    else
      segments << attribute_segment(attr, option)
    end
  end
  segments.join(" ").then do |output|
    prefix_space && !output.empty? ? " #{output}" : output
  end
end

#html_map(input, &callback) ⇒ Object



95
96
97
# File 'lib/streamlined/helpers.rb', line 95

def html_map(input, &callback)
  input.map(&callback).join
end

#text(callback) ⇒ Object



83
84
85
86
87
88
89
# File 'lib/streamlined/helpers.rb', line 83

def text(callback)
  (callback.is_a?(Proc) ? callback.pipe : callback).to_s.then do |str|
    next str if str.html_safe?

    str.encode(xml: :attr).gsub(%r{\A"|"\Z}, "")
  end
end