RubyTapas #021 - #025
021 Domain Model Events
★
around_save + yield
notify_listeners(:on_create)
Listeners作成
class PusherTaskListener
class TaskEmailListener
controller
def notify_listeners(event_name, *args)
@listeners && @listeners.each do |listener|
if listener.respond_to?(event_name)
listener.public_send(event_name, self, *args)
end
end
end
途中ピアノのBGM
022 Inline Rescue
★
typo fethc
inline rescue好きだったけど、この話では便利だけどcode smell, bad ideaって話
例外的にエラーを結果として返すのであればOKらしい
value_or_error = {}.fetch(:some_key) rescue $!
023 Tempfile
★
epub bookの作成
pandoc
pandoc -S -o book.epub ch1.md
pandoc -S --epub-metadata=metadata.xml -o book.epub ch1.md
epub metadataをxmlじゃなくてyamlから生成するスクリプト
Tempfile.open('epub_metadata') do |meta|
system('pandoc', *args)
systemコマンドとか使うスクリプトはTempfileを使うと良い
024 Incidental Change
★
def slugify(title)
title
.strip
.tr_s('^A-Za-z0-9', '-')
.downcase
end
incidental 偶発的な[偶然の・付随的な]事柄
semantic 語義の、意味(論)の
Arrayの最後のcommaとか、変更に強い書き方について
025 OpenStruct
★
JSON -> hash -> OpenStruct
OpenStruct.new(JSON.parse(data)['current_observation'])
disadvantage (compared to Struct)
- there's no listing or iterating through keys and values
- performance concerns
useful scenarios
- In quick one-off scripts like our weather report example;
- For prototyping, when first fleshing out an object model; and
- As quick-and-dirty stub objects in tests, when a full mocking framework is unavailable or inconvenient for some reason.