9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Sinatra でカスタムセッター/ゲッターを定義したり、それにより処理をフックしたりする

Posted at

Sinatra においては、 foo=(val), foo といったカスタムセッター/ゲッターをModuleのメソッドとして定義してregisterできる。

enable :foo は結局 set :foo, true と同義なので、 foo= の内部でコールバック処理を定義できたりもする。

app.rb
require 'sinatra'

module Sinatra::HookSample
  # should write setter and getter by self
  # https://github.com/sinatra/sinatra/blob/master/test/settings_test.rb#L104
  def foo=(bool)
    if bool
      puts "hook is called!"
    end
    @foo = bool
  end

  def foo
    @foo
  end
  alias foo? foo

  Sinatra.register Sinatra::HookSample
end

configure do
  enable :foo
end

get '/' do
  "foo is: #{settings.foo}"
end

フックがコールされる

$ ruby app.rb
hook is called!
[2012-11-13 14:07:27] INFO  WEBrick 1.3.1
[2012-11-13 14:07:27] INFO  ruby 1.9.3 (2012-04-20) [x86_64-darwin11.4.0]
== Sinatra/1.3.3 has taken the stage on 4567 for development with backup from WEBrick
[2012-11-13 14:07:27] INFO  WEBrick::HTTPServer#start: pid=51396 port=4567

gemとかでSinatra Extensionを公開して、なおかつenableで設定を制御したりもできるような気がする。

9
9
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?