Railsと連携する際、babble-wrapを使っていたのですが、
取得先が複数になったときに面倒だったのでラッパーライブラリを作ってみました。
Active Record風のメソッドで、Rest風にアクセスをします。
rails側はindex,show,create,update,destoryをjsonで返信するようにします。 アプリ側では適当にmodelクラスを作って、motion-rails-modelを継承し、
attr_accessorとattributes_updateに項目を追加します。
class Entries < RM::Model
attr_accessor :title, :description
def attributes_update(json)
@title = json['title']
@description = json['description']
super
end
end
利用するときは、まずurlを設定します。
class AppDelegate
def application(application, didFinishLaunchingWithOptions:launchOptions)
RM::Model.set_url("http://localhost:3000/")
@window = UIWindow.alloc.initWithFrame(UIScreen.mainScreen.bounds)
@window.rootViewController = RootViewController.alloc.init
@window.makeKeyAndVisible
true
end
end
あとは、
Entries.all do |x|
if x
p x
else
p "error"
end
end
で、http://localhost:3000/entriesにアクセスし
Entries.find(1) do |x|
if x
p x
else
p "error"
end
end
で、http://localhost:3000/entries/1
にアクセス。
@entry = Entries.new
@entry.title = "title"
@entry.description = "description"
@entry.save do |x|
if x
p x
else
p "error"
end
end
で、http://localhost:3000/entries
にpost。
@entry.title = "title2"
@entry.save do |x|
if x
p x
else
p "error"
end
end
で、http://localhost:3000/entries/1にput。
@entry.destory do |x|
if x
p x
else
p "error"
end
end
で、http://localhost:3000/entries/1にdeleteでアクセスするようになってます。
TODOとして
attributes_updateを設定しなくてもいいようにする。
エラー処理をもう少ししやすく。
0 件のコメント:
コメントを投稿