Module: Happy::Helpers::Html

Included in:
Happy::Helpers
Defined in:
lib/happy/helpers/html.rb

Instance Method Summary collapse

Instance Method Details

#escape_html(t) ⇒ Object


18
19
20
21
# File 'lib/happy/helpers/html.rb', line 18

def escape_html(t)
  # Rack::Utils.escape_html(t.to_s)
  CGI::escape_html(t.to_s)
end

#html_tag(name, options = nil, escape = true, &block) ⇒ Object


6
7
8
# File 'lib/happy/helpers/html.rb', line 6

def html_tag(name, options = nil, escape = true, &block)
  "<#{name} #{html_tag_attributes(options, escape) if options}#{block_given? ? ">#{yield if block_given?}</#{name}>" : " />"}"
end

#html_tag_attributes(options, escape = true) ⇒ Object


10
11
12
13
14
15
16
# File 'lib/happy/helpers/html.rb', line 10

def html_tag_attributes(options, escape = true)
  options.map do |k,v|
    if v
      v == true ? "#{k}" : "#{k}=\"#{ escape_html(v) }\""
    end
  end.compact.join(" ")
end

27
28
29
30
31
# File 'lib/happy/helpers/html.rb', line 27

def link_to(name, *target)
  options = target.last.is_a?(Hash) ? target.pop : {}
  target = name if target.empty?
  html_tag(:a, options.merge(:href => url_for(*target))) { name }
end

#preserve(t) ⇒ Object


23
24
25
# File 'lib/happy/helpers/html.rb', line 23

def preserve(t)
  t.chomp("\n").gsub(/\n/, '&#x000A;').gsub(/\r/, '')
end

#url_for(*what) ⇒ Object


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/happy/helpers/html.rb', line 33

def url_for(*what)
  return what.first if what.size == 1 && what.first =~ %r{://}

  result = what.flatten.inject('') do |url, item|
    url << "/%s" % case item
      when String, Symbol then item.to_s
      when NilClass then "/"
      else "%s/%s" % [item.class.to_s.tableize.pluralize, item.try(:to_param) || item.try(:to_id) || item.try(:id)]
    end

    url
  end.gsub(/\/{2,}/, '/').chomp('/')

  result == "" ? '/' : result
end