ラベル ruby の投稿を表示しています。 すべての投稿を表示
ラベル ruby の投稿を表示しています。 すべての投稿を表示

2017年12月22日金曜日

プロを目指す人のためのRuby入門を読みました

プロを目指す人のためのRuby入門を読みました

2014年からrubyやりはじめてもう3年の経験あるんですが、
改めて入門本読んでみるとまだまだ知らなかったり理解が浅いところとかあって、
読んでよかったなぁと思いました。

特に最近日付を入力させるフォームを使ってるところでちょっとどうしようか考えていたのがあったので、
以下の2つがタイムリーにささりました。

・正規表現のキャプチャの結果に名前をつけられる
text = '今日は2017年12月22日です'
result = /(?<year>\d+)年(?<month>\d+)月(?<day>\d+)日/.match(text)

p result[:year]
p result[:month]
p result[:day]

これで
"2017"
"12"
"22"
という風に取れる


・rescue演算子を使ってbegin/endを省略できる
require 'Date'
text = 'aaaaaa'
result = Date.parse(text) rescue nil
p result
parseできない文字列の時にはnilが返って来る。
これまでbegin/endって囲んでてうざいなと思っていたので、いいことを知りました。

2017年5月22日月曜日

rails4.1.6からrails5.0.3にアップデートでActiveSupport::TimeWithZoneにはまった

rails4.1.6からrails5.0.3にアップデートをした際にrspecのテストが落ちて、
それを解決するのに調べました。

環境
ruby2.3.1
rails4.1.6からrails5.0.3

rspecはこんな感じ
test_time = Time.now

user.test_at = test_time
user.save!

ごにょごにょ処理

test_atが変わらないよねっていうテスト
expect(user.test_at).to eq(test_time)

4.1.6では通っていたけど5.0.3で落ちたテスト結果
expected: 2017-05-16 16:26:54.647989000 +0900
          got: 2017-05-16 16:26:54.000000000 +0900

test_timeはTimeクラス、user.test_atはActiveSupport::TimeWithZone。
rails4.1.6のときはsave!のタイミングではTimeWithZoneのミリ秒はまるめられてなかったみたい。
4.1.6でもexpectの前にreloadすると、ミリ秒はまるめられたものに変わった。
rails5ではsave!のタイミングでミリ秒をまるめたものを保持するように変わったげ。

2017年4月13日木曜日

omniauth-facebookのバージョンあげたら値が取れなくなった

omniauth-facebookのバージョンが古かったのでバージョンをあげたところ、
取れてた氏名の値が取れなくなったので調べました。
変更前:2.0.0
変更後:4.0.0

これまでのコード
取得部分
last_name = auth.info.last_name
first_name = auth.info.first_name

config部分
config.omniauth :facebook, 'app_id', 'app_token', locale: 'ja_JP', provider_ignres_state: true, scope: 'email, public_profile'

調べてみると、configに追加するだけで取れるようになるようです。
以下のように修正しました。
config.omniauth :facebook, 'app_id', 'app_token', locale: 'ja_JP', provider_ignres_state: true, scope: 'email, public_profile', info_fields: 'email, first_name, last_name'


参考URL
http://stackoverflow.com/questions/33090322/get-first-name-and-last-name-fields-from-facebook-omniauth

2017年4月4日火曜日

active_adminのバージョンあげたらshowの処理が変わってたのでパッチ当てた

active_adminのバージョンを1.0.0.pre5にあげたらこれまでshowで見れてた
xxx_idなどが表示されなくなったので調べました。

https://github.com/activeadmin/activeadmin/blob/master/lib/active_admin/resource/attributes.rb#L27
どうやらこの処理でxxx_idやxxx_countなどの値が表示対象から外されるようになったようです。
ただ、それだと困るとの意見があったのでパッチを当てることにしました。

こちらのクックパッドさんの投稿を参考にして以下のようなパッチを書きました。
http://techlife.cookpad.com/entry/a-guide-to-monkey-patchers

require 'active_admin/version'
unless ActiveAdmin::VERSION == '1.0.0.pre5'
  raise "Confirm need this patch"
end

module ActiveAdmin
  class Resource
    module Attributes
      def reject_col?(c)
        return false
      end
    end
  end
end

2017年2月13日月曜日

carrierwaveで画像のwidthとheightを取る

carrierwaveで画像をS3にアップロードするのですが、
一定のwidthとheightより小さいものはアップロードしないように
validateではじきたいなということでwidthとheightを取得する方法を調べました。

やり方としては、modelにwidthとheightの値を格納する変数を用意して、
uploaderでwidthとheightに格納する処理を記述すればよいようです。
保存をする前にwidthとheightを取ることができるので、
自分で比較してはじいたり、validateではじいたりどちらもできます。
class Image < ActiveRecord::Base
  mount_uploader :image, ImageUploader

  attr_accessor :width, :height
end

class ImageUploader < CarrierWave::Uploader::Base
  process :store_dimensions

  def store_dimensions
    if file && model
      model.width, model.height = `identify -format "%wx%h" #{file.path}`.split(/x/)
    end
  end
end

参考URL
https://github.com/carrierwaveuploader/carrierwave/wiki/How-to:-Get-image-dimensions

2017年2月6日月曜日

MacOS Sierraでrmagickが入らない件

Mac Sierraでrmagickのインストールがエラーになったので調べました。

rubyのバージョンは以下のとおりです
ruby 2.3.1
RMagick 2.13.3
起きたエラーは以下です。
ERROR:  Error installing rmagick:
    ERROR: Failed to build gem native extension.

    /Users/xxx/.rbenv/versions/2.3.1/bin/ruby extconf.rb
checking for Ruby version >= 1.8.5... yes
checking for clang... yes
checking for Magick-config... no
Can't install RMagick 2.13.3. Can't find Magick-config in ...

調べてみるとImageMagickが入ってないからというのが多かったのですが、
ImageMagickはちゃんと入っていて、バージョンは7系でした。
ただ、バージョンが7系なのがだめなようで、これを6系のものに入れ替えると、
うまくrmagickをインストールすることができました。

brew uninstall imagemagick

brew install imagemagick@6

brew link --force imagemagick@6


参考URL
http://stackoverflow.com/questions/41647979/imagemagick-7-with-rmagick-2-16-on-macos-sierra-cant-find-magickwand-h

2017年1月31日火曜日

railsのActiveRecordでSystemStackErrorが出た件

何気なくmodel作ってenum書いてたらSystemStackError出たので調べました。
railsのバージョンは4.1.6でした。

こんな感じのmodelを作っていました。
class Sample < ActiveRecord::Base
  enum target: {
    all_user: 0,
    parent: 1,
  }
end

そして動かしてみようとすると、エラーが出ました。
irb(main):001:0* aaa = Sample.new
SystemStackError: stack level too deep
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping.rb:68:in `value_for'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/per_thread_registry.rb:47:in `public_send'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/per_thread_registry.rb:47:in `block in method_missing'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping.rb:14:in `current_scope'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping/named.rb:25:in `all'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping/named.rb:151:in `block in scope'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/model_schema.rb:335:in `compute_table_name'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/model_schema.rb:148:in `reset_table_name'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/model_schema.rb:109:in `table_name'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/core.rb:151:in `arel_table'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/core.rb:167:in `relation'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping/named.rb:33:in `default_scoped'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping/named.rb:28:in `all'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/scoping/named.rb:151:in `block in scope'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/model_schema.rb:335:in `compute_table_name'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activerecord-4.1.6/lib/active_record/model_schema.rb:148:in `reset_table_name'
... 10760 levels...
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/dependencies.rb:241:in `load'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/dependencies.rb:241:in `block in load'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/dependencies.rb:232:in `load_dependency'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/activesupport-4.1.6/lib/active_support/dependencies.rb:241:in `load'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/commands/rails.rb:6:in `call'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/command_wrapper.rb:38:in `call'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:191:in `block in serve'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:161:in `fork'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:161:in `serve'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:131:in `block in run'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:125:in `loop'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application.rb:125:in `run'
 from /Users/xxx/Documents/github/test/vendor/bundle/ruby/2.3.0/gems/spring-1.7.2/lib/spring/application/boot.rb:19:in `'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from /Users/xxx/.rbenv/versions/2.3.1/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:55:in `require'
 from -e:1:in `
'



調べてみると、enumには使ってはいけない単語を使ってるけど、
それをチェックしてないから起こっているエラーのようです。
すでに修正されていて、rails4.2からはSystemStackErrorではなく、
conflictしてるとわかるエラーが出るようです


参考URL
https://github.com/rails/rails/issues/16347
https://github.com/rails/rails/commit/94b7328b08fcc55e82bfcaa34a25ae718921ae1c

2016年11月22日火曜日

rubyのaws-sdkでALBのターゲットグループに紐付いているEC2インスタンスのIPを取得してみた

ELBからALBにリプレイスを行うにあたって、ALB配下のインスタンスのIPを取得する必要があったので調べました。
ALBはターゲットグループを割り当てる形になるので、指定したターゲットグループに紐づくインスタンスを取得すればIP取れました。

require 'aws-sdk'

alb = Aws::ElasticLoadBalancingV2::Client.new(
  region: 'ap-northeast-1',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

ec2 = Aws::EC2::Client.new(
  region: 'ap-northeast-1',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

instance_healths = alb.describe_target_health({ target_group_arn: 'xxx' })
instance_ids = instance_healths.target_health_descriptions.map {|t| t.target.id }

ec2_instances = ec2.describe_instances({ instance_ids: instance_ids })
instance_ips = ec2_instances.reservations.map { |e| p e.instances[0].public_ip_address }

2016年11月9日水曜日

aws-sdk v2でS3操作するとエラー出た

rubyのaws-sdkでS3の操作しようとしたら、エラー出たのでその時の対応。
sdkのバージョンは以下で指定
gem 'aws-sdk', "~>2.1"

出たエラーは以下のようなもの
F, [2016-11-08T11:23:44.711503 #21962] FATAL -- : 
Aws::Errors::MissingRegionError (missing region; use :region option or export region name to ENV['AWS_REGION']):
  app/xxx:12:in `new'
  app/xxx:12:in `update_s3_bucket_acl'
  app/xxx.rb:338:in `update_s3_bucket_acl'
  app/xxx.rb:323:in `block in update'
  app/xxx.rb:306:in `update'
  config/initializers/quiet_assets.rb:6:in `call_with_quiet_assets'

そのときのコードの一部がこれ
require 'aws-sdk'

s3 = Aws::S3::Resource.new(
  access_key_id: #{access_key_id},
  secret_access_key: #{secret_access_key}
)

bucket = s3.bucket(bucket_name)

対応内容はエラーにまんま書いてあるように、regionを追加しました
s3 = Aws::S3::Resource.new(
  region: 'ap-northeast-1',
  access_key_id: #{access_key_id},
  secret_access_key: #{secret_access_key}
)

S3ってregion関係ないと思うので指定いらなそうなのになと思うのは勉強不足なのでしょう...


参考URL
http://qiita.com/rikitoro@github/items/45f9c85c218343e69014
http://stackoverflow.com/questions/28825047/aws-sdk-v2-for-s3

2016年10月24日月曜日

rubyのaws-sdkでELBに紐付いているEC2インスタンスのIPを取得しようとしたらバージョン2系で記法が変わってた件

ELBに紐付いているEC2インスタンスのIPを取得していたのですが、
aws-sdkのバージョンを1系から2系に変更したらけっこう記法が変わってたので調べました。

バージョン1系
require 'aws-sdk'

elb_name = 'aaa'

AWS.config({
  access_key_id: 'xxx',
  secret_access_key: 'xxx',
  ec2_endpoint: 'xxx',
  elb_endpoint: 'xxx'
})

elb = AWS::ELB.new
lb_instances = elb.load_balancers[elb_name].instances
instance_ips = lb_instances.map { |instance| instance.public_ip_address }

バージョン2系
require 'aws-sdk'

elb_name = 'aaa'

# ELBクライアント
elb = Aws::ElasticLoadBalancing::Client.new(
  region: 'xxx',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

# EC2クライアント
ec2 = Aws::EC2::Client.new(
  region: 'xxx',
  access_key_id: 'xxx',
  secret_access_key: 'xxx'
)

lb_instances = elb.describe_load_balancers({ load_balancer_names: [elb_name] })[:load_balancer_descriptions][0][:instances]
ec2_instances = ec2.describe_instances({ instance_ids: lb_instances.map { |instance| instance.instance_id } })
instance_ips = ec2_instances.reservations.map { |e| e.instances[0].public_ip_address }

2016年7月19日火曜日

Recommendifyを入れてみたらちょっとはまった

今更なのですがRecommendifyを試してみて、普通にgem入れようとしたら入らなかったので調べました。
試した環境はMac OSX El Capitanです。

まずは以下の2つをインストール。
brew insert redis
brew insert hiredis

次にGemfileにhiredisとrecommendifyを追加。
gem install hiredis
gem install recommendify

そしてbundle installを実行。
すると、recommendifyが入らなくてエラーになりました。
Installing recommendify 0.3.8 with native extensions

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.

    /Users/xxx/.rbenv/versions/2.1.3/bin/ruby extconf.rb

make "DESTDIR=" clean
rm -f *.o

make "DESTDIR="
mkdir -p ../bin
gcc -Wall recommendify.c -lhiredis -o ../bin/recommendify
recommendify.c:4:10: fatal error: 'hiredis/hiredis.h' file not found
#include 
         ^
1 error generated.
make: *** [build] Error 1

make failed, exit code 2

Gem files will remain installed in /Users/xxx/yyy/vendor/bundle/ruby/2.1.0/gems/recommendify-0.3.8 for inspection.
Results logged to /Users/xxx/yyy/vendor/bundle/ruby/2.1.0/extensions/x86_64-darwin-14/2.1.0-static/recommendify-0.3.8/gem_make.out
An error occurred while installing recommendify (0.3.8), and Bundler cannot continue.
Make sure that `gem install recommendify -v '0.3.8'` succeeds before bundling.

調べてみたところ、recommendifyをgitからnativeブランチで取得するとよさそうです。
gem install recommendify, git: "https://github.com/danmorin/recommendify.git", branch: "native"
これで無事に入りました。

参考URL
http://blog.naberon.jp/post/2013/09/09/site-recommend/
http://d.hatena.ne.jp/itmsc/20130812/1376289715
http://qiita.com/toyama0919/items/bef2e375e9ebde9a01ba
https://github.com/paulasmuth/recommendify/issues/6

2016年6月6日月曜日

rspecでFactoryGirlでCarrierWaveのデータを作成する

CarrierWaveのイメージを入れたFactoryGirlのデータを作りたかったので調べました。

テスト用の画像データを以下に置いた状態で、
spec/support/files/test.jpg
以下の形式で記述するとよさげです。

test_image { Rack::Test::UploadedFile.new(File.join(Rails.root, 'spec', 'support', 'files', 'test.jpg'))



参考URL
http://kzy52.com/entry/2014/01/03/094308

2016年5月25日水曜日

deviseでfacebookのgraph apiから日本語の名前を取得する

deviseを使ってfacebook認証を実装していて、初期の登録時に
facebookのgraph apiからユーザーの名前を取得していたのですが、
それがローマ字のものが取れていたので、
日本語名を取るにはどこかでlocaleを指定しないといけないのだろうと調べました。

初めにこの辺にたどり着いたので、それを元に実装してみましたが、日本語名は取れませんでした
https://github.com/plataformatec/devise/wiki/How-To:-OmniAuth-inside-localized-scope
https://gist.github.com/gurix/4ed589b5551661c1536a

次にたどり着いたのがこのあたりのページで、ここの内容を参考に
omniauthの設定にlocaleを設定したら、無事に日本語名が取れるようになりました。
http://qiita.com/eleven_2012/items/d8ef22a8928c65570b82
https://teratail.com/questions/25290

設定したのはこんな感じです
config.omniauth :facebook, '#{facebook ID}', '#{key}', locale: 'ja_JP', provider_ignores_state: true, scope: 'email, public_profile'

2016年4月26日火曜日

rubyのHashでeach_with_indexの使い方

rubyのHashでeach_with_index使う時に調べててなるほどと思ったので書きました。
まずはこういうHashがあるとします。
test = { english: 100, japanese: 90 }

普通にeach_with_indexを使うとこんな感じになるかと思います。
test.each_with_index do |obj, index|
 p obj
 p obj.class
 p index
end

[:english, 100]
Array
0
[:japanese, 90]
Array
1
この形だとせっかくHashなのにkeyとvalueを分けて取れないので以下のようにやるとよいようです。
test.each_with_index do |(key, val), index|
 p key
 p val
 p index
end

:english
100
0
:japanese
90
1
これは知らなかったのですごく便利。

参考URL
http://bismar.hatenablog.com/entry/2012/12/01/215111

2016年4月19日火曜日

rubyの日付をeachでまわす

rubyで特定の日付から数日分eachでループでまわしたいときがあって、
それをやるのに2度も同じところではまったので備忘メモです。

まずはダメなパターン
(Time.now..(Time.now + 6.days)).each do |day|
 p day
end

こっちはOKなパターン
(Date.today..(Date.today + 6.days)).each do |day|
  p day
end

Timeは数値ではないので、離散形式でテストされる。 しかしTimeを用いた範囲は離散範囲ではない。
ということで、Timeではだめなので、やるときにはDateでやるか、
eachじゃない回し方をするのがよさそうです。

参考URL
http://sekai.hateblo.jp/entry/2013/10/23/081950

2016年3月31日木曜日

active_adminのscopeに設定したものが表示されない

active_adminのscopeに設定したものが表示されないと隣の席の人が言ってたので調べました

元々こうなっていました。
scope 'aaa', :need_aaa, default: false
  scope 'いいい', :need_iii, default: false

そこに以下のものを追加してたのですが、元々あった'いいい'の部分が表示されなくなってしまいました。
scope 'ううう', :need_uuu, default: false
調べたところ、scopeに日本語使ってるため表示されなくなったようです。
日本語の部分をとりあえず英語に変えたらうまく表示されるようになりました。

参考URL
http://qiita.com/SpicyCoffee/items/7b7060b93811be389893

2016年2月26日金曜日

itamaeでrbenv入れるのにはまった恥ずかしい話

ec2でrbenv入れるのにitamaeで入れようとしてたのですが、
rbenvのインストール手順を普通になぞっていったら地味にはまってしまいました。

最初に書いたレシピはこんな感じ
rbenv/default.rb
%w(
  git
  gcc-c++
  glibc-headers
  openssl-devel
  readline
  libyaml-devel
  readline-devel
  zlib
  zlib-devel
  libffi-devel
  libxml2
  libxslt
  libxml2-devel
  libxslt-devel
  sqlite-devel
  mysql-devel
  patch
).each do |pkg|
  package "#{pkg}" do
    action :install
  end
end

git '/usr/local/rbenv' do
  repository 'https://github.com/sstephenson/rbenv.git'
end

directory "/urs/local/rbenv/plugins" do
  action :create
end

git '/usr/local/rbenv/plugins/ruby-build' do
  repository 'https://github.com/sstephenson/ruby-build.git'
end

remote_file "/etc/profile.d/rbenv.sh" do
  action :create
  source "files/etc/profile.d/rbenv.sh"
  owner 'root'
  group 'root'
  mode '644'
end

execute 'install ruby' do
  command("source /etc/profile.d/rbenv.sh; rbenv install 2.3.0")
  command("source /etc/profile.d/rbenv.sh; rbenv global 2.3.0; rbenv rehash")
end

実行してみるとこんな感じ
$ bundle exec itamae ssh -i pem/test.pem -h 172.31.21.186 roles/test.rb
 INFO : Starting Itamae...
 INFO : Recipe: /home/ec2-user/deploy/xxx/roles/test.rb
 INFO :   Recipe: /home/ec2-user/deploy/xxx/cookbooks/rbenv/default.rb
 INFO :     package[git] installed will change from 'false' to 'true'
 INFO :     package[gcc-c++] installed will change from 'false' to 'true'
 INFO :     package[openssl-devel] installed will change from 'false' to 'true'
 INFO :     package[libyaml-devel] installed will change from 'false' to 'true'
 INFO :     package[readline-devel] installed will change from 'false' to 'true'
 INFO :     package[libffi-devel] installed will change from 'false' to 'true'
 INFO :     package[libxml2-devel] installed will change from 'false' to 'true'
 INFO :     package[libxslt-devel] installed will change from 'false' to 'true'
 INFO :     package[sqlite-devel] installed will change from 'false' to 'true'
 INFO :     package[mysql-devel] installed will change from 'false' to 'true'
 INFO :     package[patch] installed will change from 'false' to 'true'
 INFO :     git[/usr/local/rbenv] exist will change from 'false' to 'true'
 INFO :     directory[/urs/local/rbenv/plugins] exist will change from 'false' to 'true'
 INFO :     git[/usr/local/rbenv/plugins/ruby-build] exist will change from 'false' to 'true'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] exist will change from 'false' to 'true'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] mode will be '0644'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] owner will be 'root'
 INFO :     remote_file[/etc/profile.d/rbenv.sh] group will be 'root'
 INFO :     diff:
 INFO :     --- /dev/null 2016-02-25 02:37:28.211836042 +0000
 INFO :     +++ /tmp/itamae_tmp/1456368153.1309056 2016-02-25 02:42:33.144609603 +0000
 INFO :     @@ -0,0 +1,3 @@
 INFO :     +export RBENV_ROOT=/usr/local/rbenv
 INFO :     +export PATH="$RBENV_ROOT/bin:$PATH"
 INFO :     +eval "$(rbenv init -)"
 INFO :     execute[install ruby] executed will change from 'false' to 'true'

正常に終わったように見えてるが、rubyのバージョンが変わってない。。。
$ruby -v
ruby 2.0.0p648 (2015-12-16) [x86_64-linux]

レシピのrubyインストール部分を以下のようにコマンドを分割する形に修正
rbenv/default.rb
execute 'install ruby' do
  command("source /etc/profile.d/rbenv.sh; rbenv install 2.3.0")
end

execute 'set ruby global' do
  command("source /etc/profile.d/rbenv.sh; rbenv global 2.3.0; rbenv rehash")
end

再度実行してみる
$ bundle exec itamae ssh -i pem/test.pem -h 172.31.21.186 roles/test.rb
 INFO : Starting Itamae...
 INFO : Recipe: /home/ec2-user/deploy/xxx/roles/test.rb
 INFO :   Recipe: /home/ec2-user/deploy/xxx/cookbooks/rbenv/default.rb
 INFO :     execute[install ruby] executed will change from 'false' to 'true'
 INFO :     execute[set ruby global] executed will change from 'false' to 'true'

ちゃんとrubyのバージョンがrbenvで入れたものに変わりました
$ ruby -v
ruby 2.3.0p0 (2015-12-25 revision 53290) [x86_64-linux]


参考URL
http://qiita.com/fukuiretu/items/337e6ae15c1f01e93ec3

2016年2月16日火曜日

simplecovでrspecのテスト書いているのにカバレッジ0%のクラスがある

simplecovを使ってrailsのカバレッジを計測しているのですが、
異常に数値が低いなと思い、詳細を見ていったところ、
rspec書いているのに0%になっているクラスがいたので調べてみました。

修正前のrails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
require 'simplecov'
require 'simplecov-rcov'
〜
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start 'rails'

修正後のrails_helper.rb
ENV["RAILS_ENV"] ||= 'test'
require 'simplecov'
require 'simplecov-rcov'
SimpleCov.formatter = SimpleCov::Formatter::RcovFormatter
SimpleCov.start 'rails'

require 'spec_helper'
require File.expand_path("../../config/environment", __FILE__)
require 'rspec/rails'
require 'capybara/rails'
〜

最初はsimplecovのrequireをrequireの中で一番下に書き、
rails_helper.rbの末尾のところでSimpleCov.startさせていました。
調べたところどうやら他のモジュールが読み込まれるよりも先に
simplecovを読み込ませるようにしないといけないようです。
カバレッジ0%だったものが修正後のものではちゃんと計測できていました。


参考URL
https://github.com/colszowka/simplecov/issues/77

2015年9月21日月曜日

rubyのaws-sdkでamazonS3のaclを変更する

ユーザーの権限によって画像の公開範囲を制限する必要が出てきたので、
amazon S3のaclを動的に変えるコードを書きました。

s3 = AWS::S3.new
bucket_name = "xxx"
bucket = s3.buckets[bucket_name]
user.user_photos.each do |photo|
  o = bucket.objects[photo.url.path]
  if user.publicly?
    o.acl = :public_read
  else
    o.acl = :private
  end
end

photo.url.pathにはbucket_name以降の/からファイル名までのパスが入ります。

http://akasata.com/articles/292
http://qiita.com/ryo0301/items/791c0a666feeea0a704c
https://github.com/thoughtbot/paperclip/issues/1416

2015年8月25日火曜日

railsのformのselectでclassが当てられない

formの入力画面をrailsで作っていて、プルダウンを使うのにselectを使っていたのですが、
オプションに書かれてるclassを指定してもclassがHTMLに出力されないので調べました。

スケジュール登録での時の部分をslimでこんな感じで書いてました。
= form_for(@profile, :url => { :action => "update_schedule" }) do |f|
= f.fields_for :repeat_schedules do |rpt|
= rpt.select :start_time_hour, options_for_select((Array 0..23).map { |i| format("%02d", i) }, selected: rpt.object.start_time_hour), { class: 'form-control' }
これだとclassが出力されないため、styleが適用されませんでした。
調べたところ、classを書いている{}の前にもう一つ{}を入れるとよいようです。
こんな感じにするとちゃんとclassが出力されるようになりました。
= rpt.select :start_time_hour, options_for_select((Array 0..23).map { |i| format("%02d", i) }, selected: rpt.object.start_time_hour), {}, { class: 'form-control' }


参考URL
http://stackoverflow.com/questions/21338113/cant-add-class-on-select-form-helper-in-rails-4