2012年9月27日木曜日

テーブルに存在しないカラムをActiveRecordに追加するサンプル


「正しいMVCではModelが太る」と言われている。

俺が勝手に考える正しいMVCの実装。モデルはデータAPI!
http://kyoro353.hatenablog.com/entry/20111223/1324589389

Railsでは具体的にどうすれば良いだろうか?
apps/modelsフォルダ内の ActiveRecord を継承したクラスをカスタマイズすることだろうか。

初めの一歩として、テーブルに存在しないカラムを ActiveRecord に追加してみる。

▽現状のMigrationクラス
class CreateOnecolumnmodels < ActiveRecord::Migration
  def change
    create_table :onecolumnmodels do |t|
      t.string :name

      t.timestamps
    end
  end
end
▽現状のActiveRecordクラス
class Onecolumnmodel < ActiveRecord::Base
end
▽現状の表示結果

試しに、ActiveRecord クラスに attribute を追加してみるが、うまくいかない。

▽attributeを追加したActiveRecordクラス
class Onecolumnmodel < ActiveRecord::Base

  def initialize
    @secondname = "2nd name"
  end

  attr_accessor :secondname
end
▽追加したattributeを表示するshow.html.erb
<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @onecolumnmodel.name %>
</p>

<p>
  <b>Second Name:</b>
  <%= @onecolumnmodel.secondname %>
</p>


<%= link_to 'Edit', edit_onecolumnmodel_path(@onecolumnmodel) %> |
<%= link_to 'Back', onecolumnmodels_path %>
どうも ActiveRecord ではアクセサが機能しないようだ。
下記のように関数として実装したらうまくいった。

▽関数を追加したActiveRecordクラス
class Onecolumnmodel < ActiveRecord::Base

  def secondname
    return "2nd name"
  end
end
▽関数追加後の表示結果

2012年9月25日火曜日

Processing.js で作成した画像をJavaScriptから操作する最小サンプル


Processing.js で生成する画像は、Processing の文法で描画できる。
一度作成した画像を JavaScript で操作する最小サンプルを作ってみた。

▽作成したHTML
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script src="processing-1.4.1.js" type="text/javascript"></script>
    <script type="text/processing" data-processing-target="mycanvas">
    void setup() {
      size(200, 200);
      noLoop();
    }
    void draw() {
      background(0);
      fill(255);
      rect(10, 10, 20, 20);
    }
    void moveRect() {
      background(0);
      fill(255);
      rect(random(180), random(180), 20, 20);
    }
    </script>
  </head>
  <body>
    <p>
    <canvas id="mycanvas"></canvas>
    </p>
    <button onClick="moveRect()">Move!</ button>

    <script id="script1" type="text/javascript">
    function moveRect() {
      var p = Processing.getInstanceById("mycanvas");
      p.moveRect();
    }
    </script>

  </body>
</html>

▽実行結果

Move! ボタンを押すと白い四角形がランダムに移動する。

Processing.js の最小サンプル

画像処理プログラミング言語の Processing を JavaScript から利用できる Processing.js の最小サンプルを作ってみた。

▽作成したHTML
<pre class="prettyprint"> 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script src="processing-1.4.1.js" type="text/javascript"></script>
    <script type="text/processing" data-processing-target="mycanvas">
    void setup() {
      size(200, 200);
    }
    void draw() {
      background(0);
      fill(255);
      rect(10, 10, 20, 20);
    }
    </script>
  </head>
  <body>
    <p>
    <canvas id="mycanvas"></canvas>
    </p>
  </body>
</html>
</pre>

▽実行結果



2012年9月22日土曜日

Railsのテーブルにカラム名"type"は使えない。

Railsのテーブルにカラム名"type"を使うとエラーが発生するようだ。

仕方がないので下記のMigrationファイルを使って解決した。

class Moretinymap < ActiveRecord::Migration
  def up
    add_column :moretinymaps, :category, :integer
  end

  def down
    remove_column :moretinymaps, :type, :integer
  end
end

2012年9月16日日曜日

Ruby on RailsのRJSを利用したXMLHttpRequestの最小サンプル:その2

XMLHttpRequestを使えるようにRailsが作成したファイルを変更してみる。

▽tests_controller.rb の変更

変更前
  # GET /tests/1
  # GET /tests/1.json
  def show
    @test = Test.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @test }
    end
  end
変更後
  # GET /tests/1
  # GET /tests/1.json
  def show
    @tests = Test.find(:all)
    @test = Test.find(params[:id])
    render

  end
▽show.html.erbの変更

変更前
<p id="notice"><%= notice %></p>

<p>
  <b>Name:</b>
  <%= @test.name %>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
変更後
<p id="notice"><%= notice %></p>

<ul id='tests'>
  <%= render({:partial => "test", :collection => @tests}) %>
</ul>

<p>
  <b>Name:</b>
  <span id="test_name">AAAAA</span>
</p>


<%= link_to 'Edit', edit_test_path(@test) %> |
<%= link_to 'Back', tests_path %>
▽_test.html.erbの新規追加
<li><%= link_to test.name, test_path(test)+".js", :remote => true %></li>
▽show.js.erbの新規追加
$("#test_name").html("<%= @test.name %>");
▽サンプルデータの表示の確認

初期状態

クリック後

"XXYYZZ"のリンクをクリックすると、再読み込みなしで、Nameが "XXYYZZ"に変更された。

Ruby on RailsのRJSを利用したXMLHttpRequestの最小サンプル:その1

まずは Ruby on Rails の準備から。
Windows上の RailsInsaller を利用してみた。

▽scaffoldの実行
C:\Sites\ajaxsample\script>rails generate scaffold test name:string
      invoke  active_record
      create    db/migrate/20120914020008_create_tests.rb
      create    app/models/test.rb
      invoke    test_unit
      create      test/unit/test_test.rb
      create      test/fixtures/tests.yml
       route  resources :tests
      invoke  scaffold_controller
      create    app/controllers/tests_controller.rb
      invoke    erb
      create      app/views/tests
      create      app/views/tests/index.html.erb
      create      app/views/tests/edit.html.erb
      create      app/views/tests/show.html.erb
      create      app/views/tests/new.html.erb
      create      app/views/tests/_form.html.erb
      invoke    test_unit
      create      test/functional/tests_controller_test.rb
      invoke    helper
      create      app/helpers/tests_helper.rb
      invoke      test_unit
      create        test/unit/helpers/tests_helper_test.rb
      invoke  assets
      invoke    coffee
      create      app/assets/javascripts/tests.js.coffee
      invoke    scss
      create      app/assets/stylesheets/tests.css.scss
      invoke  scss
   identical    app/assets/stylesheets/scaffolds.css.scss
これでコントローラーを含めた必要なファイル一式を作成してもらえる。

▽DBマイグレーションの実行
C:\Sites\ajaxsample\script>rake db:migrate
(in C:/Sites/ajaxsample)
==  CreateTests: migrating ====================================================
-- create_table(:tests)
   -> 0.0940s
==  CreateTests: migrated (0.0960s) ===========================================
▽初期状態の表示の確認
http://localhost:3000/tests


▽サンプルデータの作成
# Read about fixtures at http://api.rubyonrails.org/classes/ActiveRecord/Fixtures.html

one:
  name: XXYYZZ
▽サンプルデータの登録
C:\Sites\ajaxsample\script>rake db:fixtures:load
(in C:/Sites/ajaxsample)
▽サンプルデータの表示の確認
http://localhost:3000/tests

今回はここまで。

2012年9月15日土曜日

jQueryを利用したXMLHttpRequestの最小サンプル

jQueryを利用したXMLHttpRequestの最小サンプルを作ってみた。

▽HTML側
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
      $("body").ready(function(){
        $("#disp").load("test.xml");
      })
    </script>
  </head>
  <body>
    <div id="disp"></div>
  </body>
</html>
▽取得するXML
<?xml version="1.0" encoding="UTF-8"?>
<test>GHIJK</test>
▽実行結果
GHIJK
同じことをやるのにフレームワークなしのJavaScriptの場合よりもずいぶん短くなった。

2012年9月2日日曜日

XMLHttpRequestの最小サンプル

XMLHttpRequestの最小サンプルを作ってみた。

▽HTML側
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    
    <script type="text/javascript">
    //<![CDATA[
    function onLoad() {
      var xmlhttp = false;
      if(typeof ActiveXObject != "undefined"){
        try {
          xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (e) {
          xmlhttp = false;
        }
      }
      if(!xmlhttp && typeof XMLHttpRequest != "undefined") {
        xmlhttp = new XMLHttpRequest();
      }

      xmlhttp.open("GET", "./test.xml");
      xmlhttp.onreadystatechange = function() {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
          var disp = document.getElementById("disp");
          var xmlDoc = xmlhttp.responseXML;
          disp.innerHTML = xmlDoc.getElementsByTagName('test')[0].firstChild.nodeValue;
        }
      }
      xmlhttp.send(null);
    }
    //]]>
    </script>
  </head>
  <body onload="onLoad()">
    <div id="disp">
</div>
</body>
</html>
▽取得するXML
<?xml version="1.0" encoding="UTF-8"?>
<test>ABCDEF</test>
▽実行結果
ABCDEF
▽課題
1.  ローカルのフォルダにファイルを置いただけでは動かない。Webサーバへのアップロードが必要。
2. XMLの値を変更してHTMLファイルをリロードしても、キャッシュのせいで値が更新されない。