Skip to content

Instantly share code, notes, and snippets.

@kyohei-shimada
Last active August 29, 2015 14:21
Show Gist options
  • Save kyohei-shimada/2b2d76c64604ab58f41b to your computer and use it in GitHub Desktop.
Save kyohei-shimada/2b2d76c64604ab58f41b to your computer and use it in GitHub Desktop.
RailsのちょっとしたTips

Railsじゃないのばっかりな気がするけど,Rails使ってる途中で思ったことなど

ActiveSupport

Hash#slice, slice!

ハッシュから指定したキーのみを取り出したハッシュを取得

{ a: 1, b: 2, c: 3, d: 4 }.slice(:b, :c) #=> {:b=>2, :c=>3}

https://github.com/rails/rails/blob/master/activesupport/lib/active_support/core_ext/hash/slice.rb

Object#try

指定したメソッドを持っていいればそのメソッドを実行,メソッドがなければnilを返す. 便利だが本来nilがあってはいけないようなところなどで多用すると,エラーの箇所が見えづらくなる傾向がある (本来nilは許容していないのに,エラーがとりあえず起こっているからという理由で使うのはおすすめしない.)

book = Book.first
# 1
category_name = book.category.name #=> もしcategoryというカラムがnull許容の場合bool.categoryでnilとなるためnil.nameはNoMethodError
# 2
if book.categor
  category_name = book.category.name
end
# 3
category_name = book.category.try(:name) || 'unknown'

RailsのHashだと思っているものはHashじゃないかも

controller等で何気なく受け取っているparamsとか

params.class #=> ActionController::Parameters
params.class.ancestors 
#=> [ActionController::Parameters,
 ActiveSupport::HashWithIndifferentAccess,
 Hash,
 V8::Conversion::Hash,
 JSON::Ext::Generator::GeneratorMethods::Hash,
 Enumerable,
 Object,
 Delayed::MessageSending,
 Open3,
 PP::ObjectMixin,
 V8::Conversion::Object,
 ActiveSupport::Dependencies::Loadable,
 JSON::Ext::Generator::GeneratorMethods::Object,
 Kernel,
 BasicObject]

http://api.rubyonrails.org/classes/ActiveSupport/HashWithIndifferentAccess.html

(Railsではないが)Enumerableを使いこなそう

http://docs.ruby-lang.org/ja/2.2.0/class/Enumerable.html

each.with_indexやeach_sliceとか使うとviewがスッキリ書けそう(tableとかul, liとか) 多くの場合RubyのEnumerableの機構とRailsの既存のhelperを使うとだいたいのことはできる

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment