その他
    ホーム 技術発信 DoRuby 【Rails】カレンダーで日付を入力する【protocalendar】

    【Rails】カレンダーで日付を入力する【protocalendar】

    この記事はアピリッツの技術ブログ「DoRuby」から移行した記事です。情報が古い可能性がありますのでご注意ください。

    「protocalendar」を利用すると「date_select」で日付入力していた所がJSのカレンダーで入力できるようになります。

     動作環境

    Ruby 1.8.7,1.9.3

    Rails 2.3.15

     1.「protocalendar」をダウンロード

    ここからダウンロードできます

     2.ダウンロードしたものをRailsのディレクトリに配置

    	事前に「protocalendar」用のディレクトリを各場所に作っておきます。
    	protocalendar-js-1.1.0/images/* → RAILS_ROOT/public/images/protocalendar/
    	protocalendar-js-1.1.0/javascripts/* → RAILS_ROOT/public/javascripts/protocalendar/
    	protocalendar-js-1.1.0/stylesheets/* → RAILS_ROOT/public/stylesheets/protocalendar/
    	protocalendar-js-1.1.0/lib/* → RAILS_ROOT/public/javascripts/protocalendar/
    	

     3.ヘルパー作成

    Railsの「date_select」の様に使いたいのでへルパーを作成します。

    	$ vim app/helpers/base_helper.rb
    	======================
    	def calendar_date_select(object,method,option= {},js_option= {})
    	
    	  tag = <<-EOS
    	    #{date_select object,method,option}
    	    #{image_tag("../images/protocalendar/icon_calendar.gif",:id => method)}
    	    <script type="text/javascript">
    	    SelectCalendar.createOnLoaded({
    	    yearSelect: '#{object}_#{method}_1i',
    	    monthSelect: '#{object}_#{method}_2i',
    	    daySelect: '#{object}_#{method}_3i'},
    	    triggers: ['#{method}'],
    	    lang: 'ja',
    	    showEffect: 'SlideDown', 
    	    hideEffect: 'SlideUp',
    	    startYear: #{option[:start_year]},
    	    endYear: #{option[:end_year]}
    	  EOS
    	
    	  js_option.each do |(key,value)|
    	    tag << ',' + key.to_s + ": #{value}"
    	  end
    	
    	  tag << '});</script>'
    	
    	  return tag
    	end
    	======================
    	

     4.Viewで使ってみる

    JSを読み込み、今まで「date_select」だった所を「calendar_date_select」に置き換えるだけで使う事ができます。

    	~~~~~~~~~~~
    	~~~~~~~~~~~
    	<%= javascript_include_tag '/protocalendar/protocalendar'/ %>
    	<%= javascript_include_tag '/protocalendar/lang_ja'/ %>
    	<%= javascript_include_tag '/effects'/ %>
    	<%= javascript_include_tag '/prototype'/ %>
    	~~~~~~~~~~~
    	~~~~~~~~~~~
    	
    	<%= date_select(:page, :updated_at_from %>
    	↓このように置き換えるだけ
    	<%= calendar_date_select(:page, :updated_at_from %>
    	
    	<%= date_select(:page, :updated_at_to,  :use_month_numbers => true, :include_blank => true %>
    	↓オプションを付ける場合は{}がいります。
    	<%= calendar_date_select(:page, :updated_at_to, {:use_month_numbers => true, :include_blank => true}%>
    	
    記事を共有