2012年9月26日水曜日

RubyMotion1.24でBubbleWrapを動かしてみる

( ̄(エ) ̄)彡☆

RubyMotionでWeb APIからJSONファイルを取得してみたで、BubbleWrapが動かないと書いた。

RubyMotion1.24ではconfigsをサポートしなくなったからみたいです…

Qiitaに投稿が「RubyMotionを1.24にしたらBubbleWrapが動かなくなった」

僕はRVMを使ってるのでパスはこんなかんじ

~/.rvm/gems/1.9.3/gems/bubble-wrap-1.1.3/lib/bubble-wrap/ext/motion_project_app.rb
#この2行を削除
configs.each_value &bw_config
config.validate

#追加
config.setup_blocks << bw_config

これでおっけー(>Д<)ゝ

しかーし、Qiitaにコメントが…

@Watson1978さんがブランチを作ってくれてるみたいです アリガト!(´▽`)

app_path/Gemfile
$ cat > Gemfile
source :rubygems

gem "rake"
gem 'bubble-wrap', '~> 1.1.3', :git => "git://github.com/Watson1978/BubbleWrap.git", :branch => "configs"

$ bundle install

app_path/Rakefile
# -*- coding: utf-8 -*-
$:.unshift("/Library/RubyMotion/lib")
require 'motion/project'
require 'bubble-wrap' ←追加

Motion::Project::App.setup do |app|
  # Use `rake config' to see complete project settings.
  app.name = 'app_name'
end

これだと既存のgemとごっちゃになるので、以下のオプションを付けた方がいいみたい
$ bundle install --path vendor/bundle


ぽちさんの[RubyMotion] Bundlerを使って楽をしてみた!を参考にさせてもらいましたー

「RubyMotionもくもく会」行きたかったな(つд⊂)エーン

2012年9月25日火曜日

Redcarを使ってみた

( ̄(エ) ̄)彡☆

TwitterのTLに…


Redcar is written in Ruby and runs on JRuby.

おぉ…Ruby製のオープンソースエディタ!(JRuby)

プラグインもRubyで書けるヘ(^o^)ノ

install
$ gem install redcar

Redcar+RubyMotion


plugin redcar-rubymotion
#fresh install
$ cd ~/.redcar/plugins
$ git clone git://github.com/kattrali/redcar-rubymotion.git rubymotion

#upgrade
$ cd ~/.redcar/plugins/rubymotion
$ git fetch origin && git checkout 0.8

多少、もっさり感はありますが… Javaやからかな?

今から色々触っていくよ

2012年9月23日日曜日

RubyMotionでWeb APIからJSONファイルを取得してみた

( ̄(エ) ̄)彡☆

RubyMotionでWeb APIを叩いてJSONファイルを取得ヘ(^o^)ノ

BubbleWrapが便利→BubbleWrap-GitHub

でも、RubyMotion1.24では動かない…

んじゃ、スクラッチで実装すればイイじゃね?

って事で、サンプルコードを書いてみたヽ(´ー`)ノ

app/app_delegate.rb
class AppDelegate
 def application(application, didFinishLaunchingWithOptions:launchOptions)
  #connpass api
  url = "http://connpass.com/api/v1/event/?keyword=rubymotion"

  Dispatch::Queue.concurrent.async do
    error_ptr = Pointer.new(:object)

    data = NSData.alloc.initWithContentsOfURL(NSURL.URLWithString(url), options:NSDataReadingUncached, error:error_ptr)

    json = NSJSONSerialization.JSONObjectWithData(data, options:0, error:error_ptr)
    
    #JSONファイルの内容を表示
    p json
  end
  true
 end
end

rakeするとコンソールにJSONファイルの内容が表示されたはず♪

RubyMotionではAPI を直接叩けるのでホントに便利ヽ(´ー`)ノ

2012年9月21日金曜日

RubyMotion1.24のアップデートがすごかった

( ̄(エ) ̄)彡☆

Mac OS Xの10.8.2、Xcode4.5がリリースされました。

RubyMotionも1.24にアップデートヘ(^o^)ノ

@watson1978さんがRubyMotionコミッタの一員になって初のアップデートの内容がすごい!

Retina Displayに対応
$ rake retina=4   # starts the 4-inch simulator (iPhone 5)
$ rake retina=3.5 # starts the 3.5-inch simulator (iPhone 4S and older)

Device Debugが可能に
$ rake simulator debug=1
$ rake device debug=1

‎= RubyMotion 1.24 = 

* Added support for the GM version of the iOS 6 SDK.
* Added support for the iPhone5 architecture (armv7s).
* Added new values for the `retina' option of `rake simulator': `3.5' (for
iPhone4) and `4' (for iPhone5). A `true' value will default to `3.5' in
case the simulator target is lesser than 6.0, otherwise, `4' will be used.
* Added debugging support (experimental) for both simulator and device.
Simply set the `debug' parameter to any value to attach the debugger
(ex. `rake debug=1' for simulator and `rake device debug=1' for device).
The Ruby code compiles with relevant DWARF metadata and the debugger
used is gdb. Note that the debugger experience is a work in progress and
will be significantly improved in future releases.
Check out http://www.rubymotion.com/developer-center/articles/debugging
* Fixed the `development' mode to not compile with LLVM optimizations. This
results in faster compilation times and also better debugging support,
but the code might run a bit slower. The `release' mode builds with the
entire optimization passes.
* Added to the build system the `mode' option which can be used to specify
the build mode, either `development' (default) or `release'. You can now
test your app in release mode by using `rake mode=release' for simulator
and `rake device mode=release' for device.
* Fixed the build system not to execute the user-defined application setup
block twice, which is no longer necessary with the new `mode' option.
* Removed the `archive:development' and `archive:release' tasks which are
no longer necessary with the new `mode' option.
* Added the `archive:distribution' task which builds an .ipa with distribution
settings (certificate, default entitlements, symbols stripped).
* Fixed `rake spec' to produce an .app bundle that uses a different bundle
identifier than the regular app. This is necessary in Xcode 4.5 to avoid
simulator installation issues.
* Fixed a bug in the simulator launcher when output to stdout would not be 
displayed in case the rake process was piped to another process
(ex. `rake spec | ...').
* Added the Dispatch.once method, which wraps the dispatch_once() function,
that can be useful to implement singletons. Usage: Dispatch.once { ... }.
* Added support for `define_method'. Like `attr_*', it cannot be used to 
overwrite existing Objective-C methods due to limitations of the compiler.
* Fixed a bug when converting Bignum objects into 'long long' types.
* Fixed a bug in the build system where relative source paths pointing to the
parent directory would not properly be expanded and would trigger build
failures.
* Fixed several bugs in String#% related to arguments and precision format.
* Improved String#[]= performance. 50 times faster.
* Improved String#length performance with multibyte characters. If String
includes multibyte characters, its length will be cached and reused.
500 times faster.
* Improved String#reverse performance with ASCII-compatible string. 30 times
faster.
* Improved Fixnum/Float modulo performance. 2 times faster.
* Fixed memory leaks in String#{reverse, reverse!}
* Fixed a bug when calling a method on an uninitialized Regexp object.
(ex. Regexp.allocate.to_s).
* Fixed a bug when calling NSArray#flatten(level) with 0.
* Fixed bugs in NSArray#rindex, NSArray#values_at, NSArray#values_at,
NSDictionary#values_at and Kernel.#sprintf which could raise uncatchable
exceptions.
* Fixed a bug in Dispatch::Source.timer which couldn't handle the
Dispatch::TIME_FOREVER constant for interval.
* Fixed a bug in NSArray#delete_if where nil could not be returned if the
receiver did not change.
* Added the following methods: NSArray#rotate, NSMutableArray#rotate!,
NSMutableArray#sort_by!, NSMutableArray#select!, NSMutableArray#keep_if,
NSMutableDictionary#select!, NSMutableDictionary#keep_if.

まさに盛りだくさんヽ(´ー`)ノ

業務アプリでも使ってこかな…

2012年9月20日木曜日

RubyMotion タブバー

( ̄(エ) ̄)彡☆

RubyMotionでタブバーを実装してみる

RubyMotion Tutorialはコチラ→RubyMotion Tutorial

app/app_delegate.rb
controller.tabBarItem = 
 UITabBarItem.alloc.initWithTabBarSystemItem(UITabBarSystemItemFavorites, tag: 1)

カスタムアイコンを使ってみる

app/app_delegate.rb
controller.tabBarItem = 
 UITabBarItem.alloc.initWithTitle('HOME', image:UIImage.imageNamed('home.png'), tag: 1)

connpass用のアプリを作ってるので完成したらGitHubでも公開するよーヘ(^o^)ノ

2012年9月19日水曜日

Ruby Arrayクラス

( ̄(エ) ̄)彡☆

Arrayクラスってメソッド沢山あるので…

例えば…
p Array.new(5) {|i| i }

ary[0..2] = ["a", "b"]

面白いのがこのあたりヘ(^o^)ノ
p [1, 2, 3] * 3  #=> [1, 2, 3, 1, 2, 3, 1, 2, 3]
p [1,2,3] * "," #=> "1,2,3" #self.join(times)と同じ挙動
p([1, 2, 1, 3, 1, 4, 1, 5] - [2, 3, 4, 5]) #=> [1, 1, 1, 1]

【assoc(key)】
配列の配列を検索して、その 0 番目の要素がkeyに等しい最初の 要素を返す。
ary = [[1,15], [2,25], [3,35]]
p ary.assoc(2) #=> [2, 25]

【compact】
nilを取り除いた配列を返す。
ary = [1, nil, 2, nil, 3, nil]
p ary.compact   #=> [1, 2, 3]

【delete_at】
指定した位置の要素を削除してくれる。
array = [0, 1, 2, 3, 4]
array.delete_at 2
p array #=> [0, 1, 3, 4]

【delete_if】
真になった要素を取り除いた配列を返す。
array = [30,100,50,80,79,40,95]
array.delete_if {|x| x < 80} #=> [100, 80, 95]

他にも沢山あるお→Arrayクラス

Rubyってホントに楽しい!

Railsもそうだけど、やりたい事をコードに表現できるのが良い。

2012年9月11日火曜日

Rails ActiveRecord Query

( ̄(エ) ̄)彡☆

Rails 【モデル】リレーションでView側にもUserNameを表示してみた

views/microposts/index.html.erb
<% @microposts.each do |micropost| %>
    <%= micropost.content %>

    <%= micropost.user_id %>

    <%= micropost.user.name %> ← コレ追加

    <%= link_to 'Show', micropost %>

    <%= link_to 'Edit', edit_micropost_path(micropost) %>

    <%= link_to 'Destroy', micropost, method: :delete, data: { confirm: 'Are you sure?' } %>

<% end %>

無事表示されたけど…

logをみてると1レコード毎にselect文を発行してUserデータを取得してるやん!

Processing by MicropostsController#index as HTML
  Micropost Load (0.1ms)  SELECT "microposts".* FROM "microposts" 
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 1 LIMIT 1
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 LIMIT 1
  Rendered microposts/index.html.erb within layouts/application (3.5ms)
Completed 200 OK in 9ms (Views: 7.7ms | ActiveRecord: 0.4ms)

これではレスポンスが悪くなるので修正

試してみる!

まずは、find_by_sqlを使ってみる

早くなった!

でも、なんかクエリ書くのイヤwww

Railsリファレンス(Active Record Query)を見てみると…

includesメソッドなるものが!

標準ではリレーションデータは後読みらしい(なんでか知らんが…)

controllers/microposts_controller.rb
def index
    #@microposts = Micropost.all
    @microposts = Micropost.includes(:user) ← こんな感じに修正
    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @microposts }
    end
end

Processing by MicropostsController#index as HTML
  Micropost Load (0.1ms)  SELECT "microposts".* FROM "microposts" 
  User Load (0.1ms)  SELECT "users".* FROM "users" WHERE "users"."id" IN (1, 2)
  Rendered microposts/index.html.erb within layouts/application (3.9ms)
Completed 200 OK in 8ms (Views: 7.9ms | ActiveRecord: 0.3ms)

うん、レスポンスが良くなったが…

IN句でクエリー2つ走ってるのがなんか納得いかんなー(´・ω:;.:...

2012年9月10日月曜日

Rails 【モデル】リレーション

( ̄(エ) ̄)彡☆

Rails3でのリレーション

Rails モデルリレーションよりほんの少しだけ突っ込んでみる(ホントに少しw

Micropostのedit viewでコードを入力してるけどselect boxを使って選択できるようにする

views/microposts/_form.html.erbに以下を追加
<%= f.label :user_id %>

<%= f.select :user_id, User.all.map { |e| [e.name, e.id] } %>

以上!

これでselect boxで選択する事ができるよヾ(。╹◡╹。)

index viewを見るとuser_idの値が変更されてるのが確認できます

選択ボックスのリファレンスはこちら

簡単でしょ?www

2012年9月6日木曜日

Rails CSVインポート

( ̄(エ) ̄)彡☆

まずViewでCSVファイルをアップロード出来るようにする
file_field_tagを使うー
<%= form_tag files_path, :multipart => true do %>
  ファイルを選択して下さい:(*.csv)
  <%= file_field_tag 'upload_file' %>
  <%= submit_tag "アップロード", :confirm => "ほんまにアップロードする?" %>
<% end %>

コントローラはこんな感じかな?
def create
  require 'csv'

  if params[:upload_file].blank? == false
    reader = params[:upload_file].read

    CSV.parse(reader) do |row|
      file = File.new
      file["field_name"] = row[0]
      file.save
    end
  end
end

Ruby1.9.xではFasterCSVはCSVライブラリへ組み込まれてましたー

知らなかった… ヽ(`д´;)/  うおおおお!?

ほんでHerokuへpushしてルンルン♪ ポチっ♪

UTF-8 が(´△`)ホゲ(´△`)ホゲー!(Errorメッセージ略w)

確認!
$ heroku config

LANG                => en_US.UTF-8

これだね…

なのでヽ(´ー`)ノ
$ heroku config:add LANG=ja_JP.UTF-8

変わらずw
なのでヽ(´ー`)ノ
$ heroku config:remove LANG

もう一回
$ heroku config:add LANG=ja_JP.UTF-8

でけたわ‘`,、(’∀`) ‘`,、

2012年9月3日月曜日

Rails 【Active Record】

( ̄(エ) ̄)彡☆

Rails 3.2.8

データベース作成
$ rake db:create

データベース削除
$ rake db:drop

ぜーんぶ取得
$ Members.all

id列だけ取得
$ Members.all.map(&:id)

id = 1を取得
$ Members.find_by_id(1)

id = 1 && name = "Murajun"
$ Members.find_by_id_and_name(1, "Murajun")

カラムの値が一致するレコード全てを取得
$ Members.find_all_by_admin(1)

ファインダーメソッドを使った検索
$ Members.where(name: "Murajun").order("id DESC")

name列だけ
$ Members.where(admin: 1).map{ |m| m.name }

ここに色々かいてある

Rails 【Active Record】

Rails 【View】部分テンプレート

( ̄(エ) ̄)彡☆

Rails 3.2.8

Railsでフッターを統一したい場合

/views以下に例えばshareフォルダを作成して
この中に部分テンプレートを作成する事にする

/views/layout/application.html.erb

<body>
<%= yield %>
<!--追加-->
<div id="footer">
<%= render "share/footer" %>
</div>
<!--ここまで-->
</body>

/views/share/_footer.html.erb

Copyright (C) <%= link_to "XXX Inc.", "http://www.example.com/" %> 2007-2012


全てのページに"Copyright (C) XXX Inc. 2007-2012"って表示されるはず

ページ毎に変更したい場合
<%= render "footer" %>


Rails 【View】リンク

( ̄(エ) ̄)彡☆

Rails 3.2.8

Railsのビューでリンクヾ(。╹◡╹。)

<%= link_to "HOME", root_path %>

HOME ←こんなふうに表示されるよね

こうすれば…

<%= link_to_unless_current "My Page", mypage_path %>

HOME
My Page ←こんなふうに表示される

link_to_unless_currentメソッドを使えば、リンク先が現在のページなら文字だけ表示してくれるよー