Module: Streamlined::Helpers

Included in:
Roda::RodaPlugins::Streamlined::InstanceMethods, Renderable
Defined in:
lib/streamlined/helpers.rb

Defined Under Namespace

Modules: TouchableProc

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)


83
84
85
# File 'lib/streamlined/helpers.rb', line 83

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)


74
75
76
# File 'lib/streamlined/helpers.rb', line 74

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

#html(callback, piping = nil) ⇒ Object



97
98
99
100
101
# File 'lib/streamlined/helpers.rb', line 97

def html(callback, piping = nil)
  callback = TouchableProc.run_through_pipeline(binding, callback, piping) if piping

  callback.html_safe.touch
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)


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

def html_attributes(options = nil, prefix_space: false, **kwargs) # rubocop:disable Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  options ||= kwargs
  segments = []
  options.each do |attr, option|
    next if option == false || option.nil?

    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



103
104
105
# File 'lib/streamlined/helpers.rb', line 103

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

#text(callback, piping = nil) ⇒ Object



87
88
89
90
91
92
93
94
95
# File 'lib/streamlined/helpers.rb', line 87

def text(callback, piping = nil)
  callback = TouchableProc.run_through_pipeline(binding, callback, piping) if piping

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

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