quattro_4 scribble

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

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_listeners(:#{name}, *args)
      end

      def self.to_s
        'Event(#{name})'
      end
    })
    include mod
  end

難い

def event(name)
  mod = if const_defined?(:Events, false)
          const_get(:Events)
        else
          new_mod = Module.new do
            def self.to_s
              "Events(#{instance_methods(false).join(', ')})"
            end
          end
          const_set(:Events, new_mod)
        end

029 Redirecting Output

std out and std error

$stdout.puts
$stderr.puts
STDOUT.puts


def capture_output
  old_stdout = STDOUT.clone
  pipe_r, pipe_w = IO.pipe
  pipe_r.sync    = true


output << pipe_r.readpartial(1024)

030 Backticks

%x version

%x{uname -a}

overwrite backtick

alias old_backtick `
def `(command)

031 Observer Variations

overgrown controller for a Rails project management application and redesigned it

clean separation of responsibility

class ListenerSetBuilder

  def method_missing(method_name, &block)
    event_name = method_name.to_s.sub(/^on_/, '')
    listener   = GenericListener.new(event_name, block)
    @listeners.add_listener(listener)
  end

032 Hash Default Blocks

★★

h = Hash.new do |hash, missing_key|
  hash[missing_key] = 0
end
h.default_proc # => #<Proc:0x87e23b0@-:1>
h.default_proc.call({}, :foo) # => 0

set hash keys nested to an arbitrary depth

config = Hash.new do |h,k|
  h[k] = Hash.new(&h.default_proc)
end

config[:production][:database][:adapter] = 'mysql'