Skip to content

Instantly share code, notes, and snippets.

@kyohei-shimada
Last active December 9, 2015 23:29
Show Gist options
  • Save kyohei-shimada/4344421 to your computer and use it in GitHub Desktop.
Save kyohei-shimada/4344421 to your computer and use it in GitHub Desktop.
#{Rails.root}/app/helper/application_helper.rb
module ApplicationHelper
# [example]
# simple_table(["A", "B", "C"], [ ["a1", "b1", "c1"], ["a2", "b2", "c2"] ], {:table => { :id => "hoge", :class => "huga"}, :tr => { :class => "piyo"}})
# =>
# <table id="hoge" class="huga">
# <thead>
# <tr class="piyo">
# <th>A</th>
# <th>B</th>
# <th>C</th>
# </tr>
# </thead>
# <tbody>
# <tr class="piyo">
# <td>a1</td>
# <td>b1</td>
# <td>c1</td>
# </tr>
# <tr class="piyo">
# <td>a2</td>
# <td>b2</td>
# <td>c2</td>
# </tr>
# </tbody>
# </thead>
# </table>
def simple_table(head_contents, row_contents, html_options = {})
tr_tags = []
content_tag(:table, html_options[:table] ) do
head = content_tag(:thead) do
content_tag(:tr, html_options[:tr]) do
head_contents.each do |content|
concat content_tag(:th, content, html_options[:th])
end
end
end
body = content_tag(:tbody) do
row_contents.each do |row|
tmp = content_tag(:tr, html_options[:tr]) do
row.each do |content2|
concat content_tag(:td, content2, html_options[:td])
end
end
tr_tags << tmp
end
tr_tags.each do |tag|
concat tag
end
end
head + body
end
end
# [sample1]
# simple_list(["a", "b", "c"], { :ol => true, :li => { :class => "item"} } )
# =>
# <ol>
# <li class="item">a</li>
# <li class="item">b</li>
# <li class="item">c</li>
# </ol>
# [sample2]
# simple_list(["a", "b", "c"], { :ul => { :id => "hoge", :class => "huga"}, :li => { :class => "piyo" } } )
# =>
# <ul id="hoge" class="huga">
# <li class="piyo">a</li>
# <li class="piyo">b</li>
# <li class="piyo">c</li>
# </ul>
def simple_list(items, html_options = {})
if html_options[:ol].present?
type = :ol
else
type = :ul
end
content_tag(type, html_options[type]) do
items.each do |item|
concat content_tag(:li, item, html_options[:li])
end
end
end
# how to use : same link_to helper
def link_to_only_valid_path(*args)
if args.second =~ /^(http:\/\/|https:\/\/)/
return link_to(*args)
else
all_routes = eval(Rails.application.class.parent_name)::Application.routes.routes
return link_to_if(all_routes.map{ |route| route.path.match(args.second).present? }.include?(true), *args)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment