betahikaruのブログ

まとめる前の頭の内容を吐き出す。まとめた物はQiitaなどで。

parse.com のrubyラッパー

Parse.com を使いたい。 Parse.comのSDKとして用意されているのは以下。

また、Parse.com 上で処理するCloud Code (Node.js with Express)もある。

ただ、Parse.comのSDKは、アプリ固有のキーを使って初期化する必要があるので、Javascriptのように外部にキーが公開されるのはよろしくない。やっぱりサーバサイドで処理を書きたい。。。

javaな人なのでrubyは勉強中ですが、今回SDKを組み込みたいソフトウェア(拙作のaws-portal)がruby製なので、Parse.comのREST APIrubyラッパーがないか?と探してみた。

Parse.comのrubyラッパー

たぶん以下の2つが主なGEMだとおもう。GitHubのページ見たら、作者が同じだった。

parse_resource

RailsActiveRecordのようなインタフェースでREST APIを使えるActiveResourceというgemのがあるのだが、ActiveResourceのインタフェースっぽくParse.comのAPIを使える。というものらしい。最新versionは 1.8.0(2013年リリース...)。

README.mdから、使い方を引用します。

modelはこんな感じに定義したり、検索したり、保存できるらしい。

class Post < ParseResource::Base
  fields :title, :author, :body

  validates_presence_of :title
end

p = Post.new

# validations
p.valid? #=> false 
p.errors #=> #<ActiveModel::Errors:0xab71998 ... @messages={:title=>["can't be blank"]}> 
p.title = "Introducing ParseResource" #=> "Introducing ParseResource" 
p.valid? #=> true 

# setting more attributes, then saving
p.body = "Ipso Lorem"
p.date = Time.now
p.save #=> true

# ActiveRecord style find commands
Post.find_by_title("Uncrunched") #=> A Post object

# batch save an array of objects
Post.save_all(array_of_objects)

ユーザ作成(Sign up)とログイン・ログアウトはこんな感じ。

# app/models/user.rb
class User < ParseUser
  validates_presence_of :username
  fields :name, :bio
  fields :email
end

# create a user
user = User.new(:username => "adelevie")
user.password = "asecretpassword"
user.save #=> true

# check if a user is logged in
User.authenticate("adelevie", "foooo") #=> false

# A simple controller to authenticate users
class SessionsController < ApplicationController
  def new
  end
  def create
    user = User.authenticate(params[:username], params[:password])
    if user
      session[:user_id] = user.id
      redirect_to root_url, :notice => "logged in !"
    else
      flash.now.alert = "Invalid username or password"
      render "new"
    end
  end
  def destroy
    session[:user_id] = nil
    redirect_to root_url, :notice => "Logged out!"
  end
end

すごく、"Railsっぽい"という印象。

parse-ruby-client

今多分一番使われている?っぽいGEM。公式のSDKと同じような使用感になっているっぽい。ところどころ"TODO: Implement this!"となっているのがやや気になるが…。 こちらも、README.mdから、使い方を引用します。

オブジェクトの作成は以下。

#ruby
game_score = Parse::Object.new("GameScore")
game_score["score"] = 1337
game_score["playerName"] = "Sean Plott"
game_score["cheatMode"] = false
result = game_score.save
puts result

これ、Javascript SDKとかiOSAndroid SDKのものと凄く近い。

// JavaScript
var GameScore = Parse.Object.extend("GameScore");
var gameScore = new GameScore();
 
gameScore.set("score", 1337); 
gameScore.set("playerName", "Sean Plott");
gameScore.set("cheatMode", false);
gameScore.save(null, {
  success: function(gameScore) {
    // ...
  },
  error: function(gameScore, error) {
    // ...
  }
});
// Ojbective-C
PFObject *gameScore = [PFObject objectWithClassName:@"GameScore"];
gameScore[@"score"] = @1337;
gameScore[@"playerName"] = @"Sean Plott";
gameScore[@"cheatMode"] = @NO;
[gameScore saveInBackground];

ユーザの作成(Sign up)、ログイン・ログアウトは以下。

# sign up
user = Parse::User.new({
  :username => "cooldude6",
  :password => "p_n7!-e8",
  :phone => "415-392-0202"
})
user.save

# login
user = Parse::User.authenticate("cooldude6", "p_n7!-e8")

# sign up by twitter o-auth
twitter_user = Parse::User::Twitter.new({
  "id" => "12345678",
  "screen_name" => "ParseIt",
  "consumer_key" => "SaMpLeId3X7eLjjLgWEw",
  "consumer_secret" => "SaMpLew55QbMR0vTdtOACfPXa5UdO2THX1JrxZ9s3c",
  "auth_token" => "12345678-SaMpLeTuo3m2avZxh5cjJmIrAfx4ZYyamdofM7IjU",
  "auth_token_secret" => "SaMpLeEb13SpRzQ4DAIzutEkCE2LBIm2ZQDsP3WUU"
})
twitter_user.save

あれ、ログアウトは、userをnilにすればいいのかな。 関係ないけど、rubyのnullってnilだっけ?swiftnilだけど。

まとめ

とりあえず parse-ruby-client を使えばいいんじゃないかな。