RubyTapas #006 - #010
006 Forwardable
★
同じような委譲のメソッドが多い時にシンプルに書ける
class User
attr_reader :account
def initialize(account)
@account = account
end
def first_name
account.first_name
end
def last_name
account.last_name
end
次のように書ける
require 'forwardable'
class User
attr_reader :account
extend Forwardable
def_delegators :account, :first_name, :last_name, :email_address
attr_reader :account はprivateにもできて
def_delegators :@account,
と書ける
エイリアスとしたい場合、単数系のメソッドで
def_delegator '@owner.account', :email_address, :owner_email
とも書ける
ActiveSupportでは同様のdelegateがある
composition - 組み立て、構成、合成
http://eow.alc.co.jp/composition/utf-8/
delegate - 代表(者)、委任する、委譲する
http://eow.alc.co.jp/delegate/utf-8/
007 Constructors
★★★
独自のコンストラクタを作るやり方
重要なのは
instance = allocate
Singletonになる実装
class << self
private :new
end
def self.instance
@instance ||= new
end
singletonを使った場合
class TheOne
include Singleton
end
TheOne.instance
キャッシングや、複数パターンのコンストラクタが必要なケースに関係してくる
initializeをtypoしがちなのを除けば、Rubyのコンストラクタは良いやり方だと思う
クラス名がコンストラクタなのはなんか嫌だな。クラス名のリネームとか。
008 #fetch as an Assertion
★★
ハッシュデータを使う場合で、値があることを保証する場合
auth['info']['email'] or raise ArgumentError
のようにも書けるが
auth.fetch('credentials').fetch('token')
とかくとエラー時にキーの値が分かりやすくなる
009 Symbol Literals
★
けっこうどんなものでもsymbolになる
:"foo-bar (baz)" # => :"foo-bar (baz)"
:'hello, "world"' # => :"hello, \"world\""
%s{foo:bar} # => :"foo:bar"
次のは知らなかった
post_id = 123
:"post-#{post_id}" # => :"post-123"
to_symで十分かもしれないが
あまり濫用はしたくないな
今のところ :'data-confirm' みたいのは普通にrailsで使うかな
010 Finding $HOME
Since Ruby version 1.9.2
Dir.home
Dir.home("avdi")
require 'etc'
user = Etc.getlogin
Dir.home(user)
1.9.2からだし、まだあまり使わないかな
それよりこの動画内で、vimかなんかで実行と同時にインラインで
exec_something # => "result here"
のように # => の後に実行結果が表示されるの興味深い