quattro_4 scribble

scribble 落書き (調べた事をただ落書きする)

RubyTapas

RubyTapas #211 - #217

211 Protected ★ In Ruby 2.1, the eqaulity method provided by Comparable hides exceptions and just returns false. Note that this behavior will change in a future version of Ruby. The important thing to understand is that protected access is…

RubyTapas #205 - #210

205 Comparable ★ identity, equivalence case equality and hash equality comparison operator >, ==, < spaceship operator <=> .sort include Comparable >, ==, <不要 206 Coercion ? arithmetic operations +, -, *, / 順番変えるとエラー Feet.new(5…

RubyTapas #199 - #204

199 Regexp Union ★★ "leaning toothpick syndrome" LTS つまようじ大好き症候群 Perl perlretut - Perl の正規表現のチュートリアル - perldoc.jp patterns = [ ".each do |", ".each {|", ] Regexp.union(patterns) # => /\.each\ do\ \||\.each\ \{\|/ Re…

RubyTapas #194 - #198

194 String Format ★ "Average high: %.1f, low: %.1f" % [avg_hi, avg_lo] # => "Average high: 49.7, low: 25.4" format, sprintfも同じ %.1f %d %x -> 17 (hex) %#x -> 0x17 %#X -> 0X17 %o %#o -> 027 %b %#b -> 0B10111 %e -> 2.400000e+19 %g 123.0 ->…

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.key…

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_su…

RubyTapas #179 - #183

179 Sequel ★★ PostgreSQL, MySQL, Oracle, and many others require "sequel" DB = Sequel.sqlite DB.create_table :people do primary_key :id String :name end DB.create_table :items do foreign_key :person_id, :people String :name Integer :quanti…

RubyTapas #167 - #178

167 Debugging in Gems ★★ System User (~/.gem) Version-specific Gemset-specific Project (vendor) bundle show rake bundle open rake gem install gem-open gem open rake Revert gem gem pristine rake 168 Enumerable Internals ★ Pat Shaughnessy In…

RubyTapas #162 - #166

162 PStore ★ require "pstore" store = PStore.new("todo.pstore") lister = store.transaction do |s| s.roots # => ["lister"] s.root?("lister") s.roots end read only for optimization read_only = true store.transaction(read_only) do |s| read-on…

RubyTapas #156 - #161

156 Array.new ★★ special guest chef James Edward Gray II (@JEG2) Ruby Rogues >> generator = 3.times >> generator.next => 0 >> generator.next => 1 >> generator.map {|i| i ** 2 } => [0, 1, 4] >> generator.map { :whatever } => [:whatever, :wh…

RubyTapas #152 - #155

152 Progress Bar ★★ require "ruby-progressbar" ... progress = ProgressBar.create(total: repeat) repeat.times do ... progress.increment end Progress: |=========================================================================================…

RubyTapas #147 - #151

147 Atomicity ★ 10 x 100のincremental counter jrubyだと期待通りにならない lock = Mutex.new ... # in multi threads lock.synchronize do counter += 1 end` atomic gem require "atomic" counter = Atomic.new(0) ... counter.update{|c| c + 1} atomi…

RubyTapas #141 - #146

141 Bounded Queue ? set a maximum size on our queue class def initialize(max_size = :infinite) ... def full? return false if @max_size == :infinite @max_size <= @items.size end condition_predicate wait_for_condition( @item_available, ->{@…

RubyTapas #134 - #140

134 Rake Clean ★★ コンバート sh "ebook-convert book.html #{t.name}" sh "kindlegen book.epub -o #{t.name}" Rake clean task require "rake/clean" CLEAN # => [] CLEAN.include("book.html") CLOBBER CLOBBER << "book.epub" CLOBBER << "book.mobi" $…

RubyTapas #129 - #133

129 Rake ★★ 知っている部分は多かった 知らなかった部分は file method file html_file => md_file do sh "pandoc -o #{html_file} #{md_file}" end dependencyも指定できる 指定のファイル/ディレクトリがあれば実行しないタスクを作る Rakeの基本的な使い…

RubyTapas #125 - #128

RubyTapas News このダウンローダーを採用 bf4/downloader · GitHub 別の長いscreencast The Making of Cowsays.com | Tekpub 125 And/Or ★★★ and/or と &&/|| user_name = user && user.name user_name # => "Avdi" user_name = user and user.name user_na…

RubyTapas #033 - #038

033 Classes and Constants ? Point = Class.new do attr_reader :x, :y 034 Struct from Hash ★ Beer = Struct.new(:brewery, :name, :abv, :ibu) do def self.from_hash(attributes) instance = self.new attributes.each do |key, value| instance[key] …

RubyTapas #027 - #032

027 Macros and Modules ? module Eventful def self.included(other) other.extend(Macros) end ... なんか難しい 028 Macros and Modules Part 2 ? module Macros def event(name) mod = Module.new mod.module_eval(%Q{ def #{name}(*args) notify_list…

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 lis…

RubyTapas #120 - #124

120 Outside-In ★★ configファイルとかのテスト stdinを介したテストとか output, status = Open3.capture2() output, status = Open3.capture2e(env, %W[hostconfig -c], stdin_data: example_input) config file hosts = hosts_from_input($stdin.read) Wr…

RubyTapas #115 - #119

115 pp ★★ p = puts + .inspect pp -> pretty print indentation, nested hashes 出力を変数に格納して後で扱うことができる pretty = repo.pretty_inspect pretty puts pretty 116 Extract Command Object ★ 12分 RubyNation Conference fundamental refact…

RubyTapas #110 - #114

110 Catch And Throw ★ begin parser.parse(html) unless html.nil? rescue DoneException # we are done end ↓ catch(:done) do parser.parse(html) unless html.nil? end + throw :done perfectly normal early returns 大域脱出catch, throw知らなかった …

RubyTapas #106 - #109

106 Class Accessors ★★ class MyLib class << self attr_accessor :logger end end も書けるがあまり好まない class MyLib def self.logger @logger end def self.logger=(new_logger) @logger = new_logger end end と書くのを面倒とも思わない ActiveSupp…

RubyTapas #100 - #105

100 Screen Scraping Gateway ★★ DPD – Digital Product Delivery | Sell Downloads and Content Subscriptions | Sell Downloads and Subscriptions Screen scraping Mechanize page.search('table').detect {|t| row.search('td') vcr test エピソードを個…

RubyTapas #094 - #099

094 Bang Bang ★ explicit conversion method serializeする時 (json) !! nil to_jsonとかで使う -> true/false返す、でないと null 095 Gem-Love Part 6 ? TDDしてるけどよくわからん 096 Gem-Love 7 ? 'In the last episode of RubyTapas' 恐ろしげなBGM…

RubyTapas #091 - #093

091 Ruby 2.0: Rebinding Methods ★ DCI - Data, Context and Interaction Roles source_account.extend(TransferSourceAccount) dest_account.extend(TransferDestinationAccount) Wrap source_account = TransferSourceAccount.new(account1) dest_account…

RubyTapas #016 - #020

016 super in Modules ★ defined?(super) を使う module YeOlde def hello(subject="World") if defined?(super) super else あるメソッド(sendとか)を上書きするmoduleがあった場合 original_send = Object.instance_method(:send) bound_send = original_s…

RubyTapas #088 - #090

088 Gem-Love Part 5 ? 前回のPart 4が前すぎて全く覚えてない 089 Coincidental Duplication ? Dry, eliminate duplication よくわからない 090 class << self ★ 良い点は class method -> instance methodへの変換が楽 悪い点は self. でメソッド検索で…

RubyTapas #084 - #087

084 Splat Group ★ menu.each_with_index do |*args| 次のはなかなか良い menu.each_with_index do |(name, price), i| 085 Ignore Arguments ★ .netrc ignored variable netrc_entries do |ignored, machine, ignored, login, ignored, password| # エラー…

RubyTapas #079 - #083

Java Dregs: Double Brace Initialization ? よく分からなかった April Foolらしい 079 Concat ★★ +=は新しいArrayを作る concatは+=より速い shovel-and-flatten <<+.flattenは遅い shovelと言うらしい << 080 Splat Basics ★ Destructuring -> *arrray …