RubyTapas #189 - #193
189 Assisted Refactoring
★
エディタがRubyMineになってる
- extract variable, extract method, inline variable
190 Gsub
★★★
LEXICON.each do |term, alternate| sanitized = sanitized.gsub(term, alternate) end
繰り返しは効率悪い
terms = LEXICON.keys.join("|") # => "extraterrestrial|life forms|Grey aliens|...|UFO" pattern = Regexp.new(terms) people|Sirius|Alien|Human|mind-control|men in black|UFO/ sanitized = TEXT.gsub(pattern) { |match| LEXICON[match] }
これはすごい
191 Virtual Proxy
?
- Martin Fowler's book Patterns of Enterprise Application Architecture
class VirtualProxy < BasicObject def initialize(&loader) @loader = loader @object = nil end def method_missing(name, *args, &block) @object ||= @loader.call @object.public_send(name, *args, &block) end end
BasicObject is so basic that it doesn't even define the method named class So that message is forwarded along to the proxied object just like every other message BasicObject has so few methods defined, there are fewer opportunities for conflict between methods
192 Filenames
★
- File.extname
- File.extname("/home/avdi/.profile") # => ""
- File.basename(file, File.extname(file))
- File.basename("/home/avdi/Dropbox/rubytapas/192-filenames.org", ".*")
193 Pathnames
★★
- Pathname.new("~/.emacs")
- Pathname("~/.emacs")
- path = path.expand_path
- path with a bunch of extra slashes or dots
- Pathname("/home////avdi/./.emacs").cleanpath
- helper for resolving symbolic links
- Pathname("LINK_TO_FOO").realpath
- Pathname("LINK_TO_FOO").expand_path.cleanpath
require "pathname" path = Pathname("193-pathname.org") path.file? # => true path.directory? # => false path.size # => 2835 path.mtime # => 2014-03-02 14:59:04 -0500 Pathname("BAZ").exist? # => true Pathname("BAZ").delete Pathname("BAZ").exist? # => false Pathname("parent/child/grandchild").mkpath Pathname("parent/child/grandchild").exist? # => true Pathname("parent").rmtree Pathname("parent").exist? # => false Pathname("test").open("w") do |f| f.write "Hello, world" end Pathname("test").open do |f| f.read # => "Hello, world" end
Pathname.glob("*") %W[dir1 dir2 dir3].each do |d| Pathname(d).mkpath end Pathname.glob("*").select(&:directory?)