Ruby 2.0, Rails 4.0, devise, mysql, rails_admin の初期設定メモ

ruby2.0 rails4.0の環境が整っている事を前提とします。

プロジェクト作成

$ rails new sample —database=mysql

データベースの設定(developmentのみ表記、他は割愛)

まず、以下の記述があるか確認。無ければ各自付け足してください。

# Gemfile


# Use mysql as the database for Active Record
gem 'mysql2' 


念のためターミナルから以下を実行して、mysql2をインストールする。

$ gem install mysql2

設定ファイルを編集。
mysqlのユーザーは各自作成しましょう。(追記するかも)
ここで注意点。
パスワードはクォートで囲う必要がある様です。ruby初心者のため、細かい原因が分からないのですが、多分パスワードが数字だったのが悪いのかと思います。試していませんが(試せ)、もしかしたらユーザー名も、数字の時はクォートで囲うべきなのかもしれません。
これに関してはstackoverflowに回答がありましたが、どこにあったか分からなくなりました(探せ)。

# config/database.yml

development:
  adapter: mysql2
  encoding: utf8
  database: sample_db
  pool: 5
  username: sample_mysql_user  
  password: ‘user_password’  
  host: localhost
  socket: /tmp/mysql.sock

その後ターミナルに戻り、以下を実行。
db:setupはdb:createの処理もやってくれるので、db:createは冗長なのですが、下に書くエラーが出るのがdb:createのタイミングなので、一応。

$ rake db:create
$ rake db:migrate

これでデータベースとテーブルの作成が完了。

config/database.ymlにてパスワードを囲わなかった場合のエラーは以下のようになる。

$ rake db:create —trace

と叩くと

** Invoke db:create (first_time)
** Invoke db:load_config (first_time)
** Execute db:load_config
** Execute db:create
no implicit conversion of Fixnum into String

……….

Couldn’t create database for {“adapter”=>”mysql2”, “encoding”=>“utf8”, “database”=>”sample_db”, “pool”=>5, “username”=>”sample_mysql_user”, “password”=>user_password”, “host”=>”localhost”, “socket”=>”/tmp/mysql.sock”}

と表示され、rake db:migrateを叩いても同じようなエラーとなります。
一応メモとして。

deviseとrails_adminの設定

まずGemfileに以下を記述

# Gemfile
     .
     .
     .
gem ‘devise’
gem ‘rails_admin'

その後、コンソールにて

$ bundle install

と叩く。

devise

$ rails g devise:install


===============================================================================
Some setup you must do manually if you haven't yet:
  1. Ensure you have defined default url options in your environments files. Here
     is an example of default_url_options appropriate for a development environment
     in config/environments/development.rb:
       config.action_mailer.default_url_options = { :host => 'localhost:3000' }
     In production, :host should be set to the actual host of your application.
  2. Ensure you have defined root_url to *something* in your config/routes.rb.
     For example:
       root :to => "home#index"
  3. Ensure you have flash messages in app/views/layouts/application.html.erb.
     For example:
       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>
  4. If you are deploying on Heroku with Rails 3.2 only, you may want to set:
       config.assets.initialize_on_precompile = false
     On config/application.rb forcing your application to not access the DB
     or load models when precompiling your assets.
  5. You can copy Devise views (for customization) to your app by running:
       rails g devise:views
===============================================================================


上の指示通りに設定を行う。

1
# config/environments/development.rb 
     .
     .
     .
     # for devise
     config.action_mailer.default_url_options = { :host => 'localhost:3000' } 
end
2

まだcontrollerを作成していないので、後回し

3
# app/views/layouts/application.html.erb
     .
     .
     <%= yield %>

       <p class="notice"><%= notice %></p>
       <p class="alert"><%= alert %></p>
     .
     .
4

今はrails4.0以上を使う事前提なので、この設定は必要なし。

5

viewを作成する際に行う。


これで、devise側から指示された設定はひとまず完了。

次にUserモデルを作成する。
Userには管理者であるかないかという属性を持たせたい。
今回は、deviseのhowtoにあるoption 2を選択する(以下URLを参照)。
https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role#option-2---adding-an-admin-attribute

そこで、次のコマンドを叩く

$ rails g devise User
$ rails generate migration add_admin_to_users admin:boolean

そして、生成されたmigrationファイルを以下のように編集。

# db/migrate/${DATE_CREATED}_add_admin_to_users.rb


class AddAdminToUsers &lt; ActiveRecord::Migration
  def self.up
    add_column :users, :admin, :boolean, :default => false
  end

  def self.down
    remove_column :users, :admin
  end
end

マイグレーションを行う前に、まずrails_adminの設定をする。

rails_admin

$ rake g rails_admin:install

2つ聞かれるが、今回はadminをuserに組み込む事にしたので、両方、空のenterを押してしまえばよい。

これでrails_adminの設定は完了。簡単。


deviseとrails_adminの設定が終わったので

$ rake db:migrate

する。


あとはcontrollerを作成して、routeを追加して、viewを作成する。


テスト出来るように、手順を残しておく。
今回はroot home#indexを使う。deviseが例を書いてくれているrouteです。

$ rails g controller home index
# app/controllers/home_controller.rb

class HomeController < ApplicationController

  before_filter :authenticate_user! # 追加

  def index
  end
end 

こうして、railsサーバーを立ち上げる。

$ rails s

http://localhost:3000/

を見てみると、deviseにより作られた画面が表示されるので、sign upボタンを押して、登録すると、rails_adminの画面を見る事が出来る。

以上。
随時追記or変更して行く予定。

kobold2d v2.1.0 Xcode5対応

記事にするのが遅れましたが、kobold2d v2.1.0をxcode5で使用可能にするパッチが、作者から出ています。


対応が切られたと思っていましたが、対応してくれました。ありがたく使わせてもらいましょう。

-performSelector:withObject:afterDelay:を用いて、複数のアニメーションを実行するときの注意点

今回ははまった。

なので共有として書いておく


以下のようなコードを書いていた

[self performSelector:@selector(animate1) withObject:nil afterDelay:0.5f];
[self animate2];
[self performSelector:@selector(animate3) withObject:nil afterDelay:0.5f];


animate1~3は内部でUIViewのアニメーションを実行するメソッドが書かれており、durationは全て0.5fである。


これを書いたとき、以下のようにアニメーションされる事を期待した。

  1. animate2が実行される
  2. animate2の終了直後、”同時に”animate1とanimate3が実行される


だが、実際は以下のように動作した。

  1. animate2が実行される
  2. . animate1が実行される
  3. 2.からほんの少しだけ遅れてanimate3が実行される

[self animate2]の実行により、内部の時計が少しだけ進んでしまった事に依るanimate3の遅延だと考えられる。

今回はいくつかのファイルにまたがってこのような記述を行ったため、completion^()を使うのをさけてしまった。
出来るだけcompletionを使う実装を心がけたい。

iOSでEasing

iOSとくにUIKitを使っている場合、デフォルトではイージングが4種類しかありません。

そこでおすすめなのが以下のイージングライブラリです。
https://github.com/bryanoltman/CAAnimation-EasingEquations:CAAnimation-EasingEquations

準備

  1. QuartzCoreフレームワークをプロジェクトにリンクする
  2. CAAnimation+EasingEquations.h/m を追加
  3. イージングを使用したいファイルに上記ヘッダーをインポートする

使い方

CAAnimationを使用しているので、UIViewではなくCALayerをターゲットにします。
http://easings.net/jaここにのっているイージングを使用可能です。

具体的な使用方法は以下の通り

CALayerのプロパティをキーとする
    [CAAnimation addAnimationToLayer:animatedView.layer
                         withKeyPath:@"opacity"
                            duration:1
                                  to:0
                      easingFunction:CAAnimationEasingFuctionEaseInBounce];
CATransform3Dを使用する
    CATransform3D tr;
    tr = CATransform3DMakeScale(2.5, 2.5, 1.0);
    tr = CATransform3DTranslate(tr, 95, 0, 0);
    [CAAnimation addAnimationToLayer:animatedView.layer
                            duration:1
                           transform:tr
                      easingFunction:CAAnimationEasingFuctionEaseOutBack];


非常に簡単に使用出来るので、UIKitのイージングに不満を持っているようでしたら是非。
AppleさんEasingくらいさっさと追加してくれればいいのに…)

ARC環境におけるNSTimerの再利用(再起動)

NSTimerは -invalidate メソッドをコールするとARCによって回収されてしまう。
なので、再起動のためには再度タイマーの内容を決定してやる必要がある。


具体的な方法を示す。

適当なところで、NSTimer *timerのインスタンスを確保しておく。
そして、以下のようにメソッドを実装。

タイマーを起動するときは -startUpdate、タイマーを終了するときは -stopUpdateを呼んでやれば良い。

-(void)update:(NSTimer*)currentTimer
{
     // update
}


-(void)startUpdate
{
    timer = nil;
    timer = [NSTimer scheduledTimerWithTimeInterval:1.0f/60.0f
                                                                      target:self
                                                                   selector:@selector(update:)
                                                                   userInfo:nil
                                                                    repeats:YES];
    [timer fire];
}
-(void)stopUpdate
{
    [timer invalidate];
}