Open5

railsのメソッド

masamasa

Moduleの関数

masamasa

const_set
既存のmoduleに定数・値を追加することができる。

Foo.const_set(:FOO, 123)
Foo::FOO # => 123
masamasa

module_exec(class_exec)
既存module(class)に対して、ブロックで渡した関数が定義できるようになる。

class Thing
end
c = 1

Thing.class_exec{
  def hello() 
    "Hello there!" 
  end

  define_method(:foo) do   # ローカル変数がブロックの外側を参照している
    c
  end
}

t = Thing.new
p t.hello()            #=> "Hello there!"
p t.foo()

block関数なので、下記の書き方もできる。

Thing.class_exec do 
  def hello() 
    "Hello there!" 
  end

  define_method(:foo) do   # インスタンス変数
    c
  end

  const_set(:hoge, 'd') # クラス定数
end
masamasa

bang!のメソッド

masamasa

find_by!

  • 見つからない場合、404(ActiveRecord::RecordNotFound)が返却される。
  • rescue_from ActiveRecord::RecordNotFound, with: :not_foundとすると、not_found関数でエラーのレスポンスをオーバーライドできる。