Skip to content

Instantly share code, notes, and snippets.

@a2ikm
Created May 29, 2015 06:59
Show Gist options
  • Save a2ikm/cc2eb7e3e33b45f99682 to your computer and use it in GitHub Desktop.
Save a2ikm/cc2eb7e3e33b45f99682 to your computer and use it in GitHub Desktop.
middlemanでカレンダーを生成するヘルパ
require "date"
#
# <%= calendar year: 2015, month: 4 do |date, is_this_month|
# <td>
# <%- if is_this_month %>
# <%= date.day %>
# <%- else %>
# <span class="text-muted"><%= date.day %></span>
# <%- end %>
# </td>
#
module CalendarHelper
def calendar(year:, month:, &block)
Calendar.new(year, month).render(self, &block)
end
class Calendar
attr_reader :year, :month
def initialize(year, month)
@year = year
@month = month
end
def render(template, &block)
@template = template
@buffer = ""
render_table do
render_header
render_weeks(&block)
end
@buffer
end
def render_table
@buffer += %Q{<table class="table table-bordered">}
yield
@buffer += %Q{</table>}
end
def render_header
@buffer += %Q{<thead><tr>}
%w(日 月 火 水 木 金 土).each do |wday|
@buffer += %Q{<th>#{wday}</th>}
end
@buffer += %Q{</tr></thead>}
end
def render_weeks(&block)
@buffer += %Q{<tbody>}
weeks.each do |week|
render_week(week, &block)
end
@buffer += %Q{</tbody>}
end
def render_week(week, &block)
@buffer += %Q{<tr>}
week.each do |(date, is_this_month)|
@buffer += capture_html(date, is_this_month, &block)
end
@buffer += %Q{</tr>}
end
def weeks
first_date = Date.new(year, month, 1)
last_date = Date.new(year, month, -1)
result = []
last_week = []
first_date.wday.downto(1) do |n|
date = first_date - n
last_week << [date, false]
end
first_date.upto(last_date) do |date|
if date.sunday? && last_week.any?
result << last_week
last_week = []
end
last_week << [date, true]
end
1.upto(6 - last_date.wday) do |n|
date = last_date + n
last_week << [date, false]
end
result << last_week
result
end
def capture_html(*args, &block)
engine = File.extname(block.source_location[0])[1..-1].to_sym
handler = ::Padrino::Helpers::OutputHelpers.handlers[engine].new(@template)
result = handler.capture_from_template(*args, &block)
ActiveSupport::SafeBuffer.new.safe_concat(result)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment