RubyTapas #184 - #188
184 Sequel, Postgres, JSON
★
PG extension
require "sequel" Sequel.extension(:pg_json) Sequel.extension(:pg_json_ops) ... DB[:dpd_subscriber_dump].import([:subscriber], data.map{|s| [Sequel.pg_json(s)]})
- DB = Sequel.connect
- row = DB[:dpd_subscriber_dump].detect
- DB.alter_table :dpd_subscriber_dump do
- add_index Sequel.lit
185 Two Refactorings
★
functional programming style
def enumerate_episodes(summaries, last_number) summaries.inject(last_number) do |last_number, ep_summary| # !> shadowing outer local variable - last_number episode = yield ep_summary, last_number + 1 episode.number end end
でも理解しにくい
別の方法
class EpisodeEnumeration def initialize @next_number = 1 end def number_episode(episode) number = episode.number if number @next_number = number else episode.number = @next_number end @next_number += 1 end end ... episode_enumeration = EpisodeEnumeration.new ... episode_enumeration.number_episode(episode)
Embrace state
3つ目
Third approach is to go to the source of the data, and make sure there are no episodes with the number missing from their titles in the first place!
186 Keyword Arguments
★
引数の必須チェック、エラーの出し方とか 引数を打ち間違えたときの動きとか
次のものはtypoが分からない
def order_burger(customer_name, options={}) has_cheese = options.fetch(:cheese)
def order_burger(customer_name, options={}) patty_type = options.delete(:patty) { :beef } ... if options.any? raise ArgumentError, "Unrecognized option(s): #{options}" end
cheeseにデフォルト値が無い
def order_burger(customer_name, patty: :beef, cheese:, onions: true, bacon: false)
def order_burger(customer_name, patty: :beef, cheese:, onions: true, bacon: false) ... order_burger("Grimm", cheese: false, onion: false) # ~> -:11:in `<main>': unknown keyword: onion (ArgumentError)
187 More Keyword Arguments
★
2 more advanced use cases
def order_meal(customer_name, fries: true, drink: "cola", **options) order_burger(customer_name, options)
cheeseをtrueにするラッパー
def order_cheeseburger(customer, **options) order_burger(customer, cheese: true, **options)
188 More Keyword Arguments
★
Jim Weirich
he was a RubyTapas viewer
Today's episode is about one of the ideas he sent me in that email.
alias of raise
fail "Abandon ship!"
most of the Ruby world has embraced #raise over #fail
Not Jim Weirich, though—in his projects, he used both methods
When indicating a failure for the first time, he would use fail.
use raise when re-raising an exception
I'm a big fan of conventions that give extra semantic information to code readers. Lately I've started to use this one in my own code