Madogiwa Blog

主に技術系の学習メモに使っていきます。

RubyonRails:RubyonRailsチュートリアル回答メモ(第1章)

Ruby on Rails チュートリアルの演習回答メモです。

第一章「ゼロからデプロイまで」

演習1

問1

リスト1.8のhelloアクションを書き換え、「Hello, world!」の代わりに「hola, mundo!」と表示されるようにしてみましょう。課外作業: Railsの表示では「非ASCII文字」もサポートされています。スペイン語特有の逆さ感嘆符「¡」を含む「¡Hola, mundo!」を表示してみましょう (図1.19)20 

回答

application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def hello
      render text:"hola, mundo!"
  end
end
問2

リスト1.8のhelloアクションを複製して、第2のアクションgoodbyeを追加しましょう。このアクションは、「goodbye, world!」というテキストを表示します。リスト1.10のルーティングを編集して、ルートルーティングの割り当て先をhelloアクションからgoodbyeアクションに変更します (図1.20)。

回答

application_controller.rb

class ApplicationController < ActionController::Base
  # Prevent CSRF attacks by raising an exception.
  # For APIs, you may want to use :null_session instead.
  protect_from_forgery with: :exception
  def hello
      render text:"hola, mundo!"
  end

  def goodbye
      render text:"goodbye, world!!"
  end

end

routes.rb

Rails.application.routes.draw do
  root 'application#goodbye'
end

とりあえず、一章はここまで

javascript:<input type="date">の初期値に現在日付を設定する方法

自分で作っている時に少しハマったので、φ(..)メモメモ

<input type="date">の日付の設定について

<input type="date" id="limit">

HTML5で新しく追加された日付を入力するためのフォーム部品は、
時刻の形式を"yyyy-mm-dd"で設定しなければいけません。

なにも考えずに設定してしまうと・・・

しかし、下記のように何も考えずに月日を取得し、設定すると形式が合わずErrorとなってしまいます。。。

  var month = date.getMonth() + 1 // 返り値は、1 ~ 12
  var day = date.getDate() // 返り値は、1 ~ 31

※返り値が一桁となる場合、mmまたはddの形式とならない。

解決作

日付を取得した後に指定桁数にゼロ埋めしてあげる。
以下のサンプルでは、toTargetDigitsで対象(num)と何桁まで0埋めするか(digits)を指定し、
指定桁数まで文頭に'0'を追加しています。

サンプルソース

  var date = new Date()
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var toTargetDigits = function (num, digits) {
    num += ''
    while (num.length < digits) {
      num = '0' + num
    }
    return num
  }
  
  var yyyy = toTargetDigits(year, 4)
  var mm = toTargetDigits(month, 2)
  var dd = toTargetDigits(day, 2)
  console.log(yyyy+'-'+mm+'-'+dd)

参考にさせて頂いたページ

tagamidaiki.com
qiita.com

Bootstrap:btn-groupで結合したボタンをインラインで表示する方法

Bootstrapで結合したボタンをインラインで表示させる際にハマったので、メモφ(..)

結果としては、下記のように<div></div>じゃなくて<span></span>を使用すれば、
問題ないっぽい。

<span class="btn-group">
     <button class="btn btn-xs btn-success">ボタン1</button>
     <button class="btn btn-xs btn-success">ボタン2</button>
</span>

参考にしたページ
qiita.com

javascript:Twitter投稿画面に任意の文字列を初期設定させる方法

外部サービスからTwitterへ投稿する必要があり、
TwitterAPI等は使いたくなかったのでいろいろ調査した結果をメモ。

Twitterの投稿画面に任意の文字列を初期設定させるためには、
投稿画面のurlの"text="以降にURLエンコードした文字列を設定して上げれば良い。
TwitterAPI等を使わなくてもTweetを投稿することは出来る。
("#"をつければ、ハッシュタグとして認識される。)
※もっと良いやり方があるかもしれませんが。。。

(function() {
        window.open(
            "https://twitter.com/intent/tweet?text=" + 
            encodeURIComponent(
                "hogehogehoge"
                +"#hugahuga"
            )
        );
})();