09. Интроспекция

09. Интроспекция

09. Интроспекция

7 ноември 2012

Днес

Преди това

Интроспекция

Интроспекция

Code smell

Интроспекция на ОО йерархията

Разглеждане на обекти

методите им

'foo'.methods.size  # 167
String.methods.size # 106

Разглеждане на обекти

Методите им

Методи на обекти

Пример

class Ruby
  def self.author() 'Matz' end

  def version() '1.9.3' end
  def repository() 'Git' end
  def implementation() 'MRI C' end

  protected :repository
  private :implementation
end

Ruby.public_instance_methods     # [:version, :psych_to_yaml, :to_yaml_properties, :to_yaml, :nil?, :===, :=~, :!~, :eql?, :hash, :<=>, :class, :singleton_class, :clone, :dup, :initialize_dup, :initialize_clone, :taint, :tainted?, :untaint, :untrust, :untrusted?, :trust, :freeze, :frozen?, :to_s, :inspect, :methods, :singleton_methods, :protected_methods, :private_methods, :public_methods, :instance_variables, :instance_variable_get, :instance_variable_set, :instance_variable_defined?, :instance_of?, :kind_of?, :is_a?, :tap, :send, :public_send, :respond_to?, :respond_to_missing?, :extend, :display, :method, :public_method, :define_singleton_method, :object_id, :to_enum, :enum_for, :gem, :psych_y, :==, :equal?, :!, :!=, :instance_eval, :instance_exec, :__send__, :__id__]
Ruby.protected_instance_methods  # [:repository]
Ruby.private_instance_methods    # [:implementation, :Digest, :initialize_copy, :remove_instance_variable, :sprintf, :format, :Integer, :Float, :String, :Array, :warn, :raise, :fail, :global_variables, :__method__, :__callee__, :eval, :local_variables, :iterator?, :block_given?, :catch, :throw, :loop, :caller, :trace_var, :untrace_var, :at_exit, :syscall, :open, :printf, :print, :putc, :puts, :gets, :readline, :select, :readlines, :`, :p, :test, :srand, :rand, :trap, :exec, :fork, :exit!, :system, :spawn, :sleep, :exit, :abort, :load, :require, :require_relative, :autoload, :autoload?, :proc, :lambda, :binding, :set_trace_func, :Rational, :Complex, :gem_original_require, :Pathname, :y, :URI, :rubygems_require, :initialize, :singleton_method_added, :singleton_method_removed, :singleton_method_undefined, :method_missing]
Ruby.singleton_methods           # [:author, :yaml_tag]

Методи на обекти

Инстанционни променливи

Инстанционни променливи

Пример

class Foo
  def initialize
    @baba = 42
  end

  def touch
    @touched = true
  end
end

foo = Foo.new

foo.instance_variables # [:@baba]
foo.touch
foo.instance_variables # [:@baba, :@touched]

Инстанционни променливи

Пример

class Foo
  def initialize
    @baba = 42
  end
end

foo = Foo.new

foo.instance_variable_defined? :@baba # true

foo.send(:remove_instance_variable, :@baba)
foo.instance_variable_defined? :@baba # false

Константи

Константи

Константи

Regexp.constants          # [:IGNORECASE, :EXTENDED, :MULTILINE, :FIXEDENCODING, :NOENCODING]
Object.constants.take(5)  # [:Object, :Module, :Class, :BasicObject, :Kernel]
Object.constants.size     # 125

Константи

не правете така

String # String
Object.const_set(:String, Fixnum)
String # Fixnum

Глобални променливи

Kernel#global_variables ще ви върне списък с всички глобални променливи
дефинирани към момента. Например:

puts global_variables.map { |var| var.to_s.ljust(16) }
                     .each_slice(4)
                     .map { |vars_per_line| vars_per_line.join(' ') }
                     .join("\n")

Глобални променливи

$;               $-F              $@               $!
$SAFE            $~               $&               $`
$'               $+               $=               $KCODE
$-K              $,               $/               $-0
$\               $_               $stdin           $stdout
$stderr          $>               $<               $.
$FILENAME        $-i              $*               $?
$$               $:               $-I              $LOAD_PATH
$"               $LOADED_FEATURES $VERBOSE         $-v
$-w              $-W              $DEBUG           $-d
$0               $PROGRAM_NAME    $-p              $-l
$-a              $binding         $1               $2
$3               $4               $5               $6
$7               $8               $9

Локални променливи

foo          = :bar
die_antwoord = 42

local_variables # [:foo, :die_antwoord, :_xmp_1359712245_28221_918437]

defined?

defined?

unless defined? cache
  cache = true
end

defined?

gotcha

x = 42 unless defined? x
x # nil

defined?

defined? 1             # "expression"
defined? foo           # nil
defined? puts          # "method"
defined? String        # "constant"
defined? $&            # nil
defined? $_            # "global-variable"
defined? Math::PI      # "constant"
defined? answer = 42   # "assignment"
defined? 42.abs        # "method"

block_given?

Можете да ползвате Kernel#block_given?, за да проверите дали
някой ви е подал блок, например:

def block_or_no_block
  if block_given?
    'We got a block, go this way...'
  else
    'No block man, go that way...'
  end
end

block_or_no_block     # "No block man, go that way..."
block_or_no_block {}  # "We got a block, go this way..."

ObjectSpace

ObjectSpace.each_object

ObjectSpace.each_object.count          # 52658
ObjectSpace.each_object(String).count  # 32152
ObjectSpace.each_object(Float).to_a    # [2.718281828459045, 3.141592653589793, NaN, Infinity, 2.220446049250313e-16, 1.7976931348623157e+308, 2.2250738585072014e-308, 0.0, 0.0, 0.0, 0.0, 0.3, -Infinity, Infinity]
ObjectSpace.each_object(Class).count   # 413

ObjectSpace.each_object(Class) do |klass|
  # Do something with klass
end

ObjectSpace.count_objects

Дава проста статистика на бройките обекти в паметта по типове. Връща хеш. Например:

puts ObjectSpace.count_objects
      .map { |type, count| "#{type}:".ljust(10) + count.to_s.rjust(7) }
      .each_slice(3)
      .map { |counts_per_row| counts_per_row.join('    ') }
      .join("\n")

ObjectSpace.count_objects

Резултати

TOTAL:     419019    FREE:      289687    T_OBJECT:   12958
T_CLASS:      880    T_MODULE:      34    T_FLOAT:        8
T_STRING:   85708    T_REGEXP:     175    T_ARRAY:    21544
T_HASH:       707    T_STRUCT:       1    T_BIGNUM:       6
T_FILE:         7    T_DATA:      2188    T_MATCH:      643
T_COMPLEX:      1    T_NODE:      4436    T_ICLASS:      36

ObjectSpace._id2ref

id = 'larodi'.object_id   # 84172900
ObjectSpace._id2ref(id)   # "larodi"

Деструктори в Ruby?

ObjectSpace.define_finalizer

foo = 'Memory is plentiful!'
ObjectSpace.define_finalizer foo, proc { puts 'foo is gone' }
ObjectSpace.garbage_collect

foo = nil
ObjectSpace.garbage_collect

# Тук proc-ът от по-горе бива извикан
# и на STDOUT се извежда "foo is gone"

Object#method(method_name)

class Person
  def name
    'Matz'
  end
end

Person.new.method(:name) # #<Method: Person#name>

Класът Method

Или какво може да правите с обектите му

Method#call

class Person
  attr_accessor :name
end

someone = Person.new
someone.name = 'Murakami Haruki'

name_method = someone.method(:name)
name_method.call  # "Murakami Haruki"

Method#arity и #parameters

def foo(x, y, z); end

method(:foo).arity      # 3
method(:foo).parameters # [[:req, :x], [:req, :y], [:req, :z]]

def bar(x, y, z = 1); end

method(:bar).arity      # -3
method(:bar).parameters # [[:req, :x], [:req, :y], [:opt, :z]]

Proc#arity

Proc.new { |x| }.arity      # 1
lambda { |x, y| }.arity     # 2

Method#source_location

require 'set'
Set.new.method(:to_a).source_location # ["/Users/.../ruby-1.9.3/lib/ruby/1.9.1/set.rb", 144]

class Set; def to_a; super; end; end
Set.new.method(:to_a).source_location # ["-", 4]

Необвързани методи

Необвързани методи

class Person
  attr_reader :name

  def initialize(name)
    @name = name
  end
end

stefan = Person.new 'Stefan'
mitio  = Person.new 'Mitio'

stefan.name                           # "Stefan"

stefans_name = stefan.method(:name)
stefans_name.call                     # "Stefan"
stefans_name.unbind.bind(mitio).call  # "Mitio"

Hooks

Куки

Добавяне и махане на методи

Добавяне и махане на методи

Пример

module Foo
  def self.method_added(name)
    puts "A-ha! You added the #{name} method!"
  end
end

module Foo
  def bar
  end
end # Извежда "A-ha! You added the bar method!"

Още hooks

Hooks

Човъркане с виртуалната машина

GC.methods - Object.methods # [:start, :enable, :disable, :stress, :stress=, :count, :stat]
GC.constants                # [:Profiler]

GC::Profiler

Профилиране на garbage collector-а

GC::Profiler.enable
require 'active_support/ordered_hash'
puts GC::Profiler.result

Резултати:

GC 8 invokes.
Index    Invoke Time(sec)       Use Size(byte)     Total Size(byte)         Total Object                    GC Time(ms)
    1               0.706              2889840             16818080               420452        23.71699999999998809130

За десерт

Kernel#set_trace_func(proc)

Събития

Kernel#set_trace_func

Пример

tracer = proc do |event, file, line, id, binding, classname|
   printf "%8s %s:%-2d %15s %15s\n", event, file, line, id, classname
end

set_trace_func tracer

class Foo
  def bar
    a, b = 1, 2
  end
end

larodi = Foo.new
larodi.bar

Kernel#set_trace_func

Резултати

c-return t.rb:5   set_trace_func          Kernel
    line t.rb:7
  c-call t.rb:7        inherited           Class
c-return t.rb:7        inherited           Class
   class t.rb:7
    line t.rb:8
  c-call t.rb:8     method_added          Module
c-return t.rb:8     method_added          Module
     end t.rb:11
    line t.rb:13
  c-call t.rb:13             new           Class
  c-call t.rb:13      initialize     BasicObject
c-return t.rb:13      initialize     BasicObject
c-return t.rb:13             new           Class
    line t.rb:14
    call t.rb:8              bar             Foo
    line t.rb:9              bar             Foo
  return t.rb:10             bar             Foo

Kernel#trace_var

Kernel#trace_var

Пример

trace_var :$_ do |value|
  puts "$_ is now #{value.inspect}"
end

$_ = "Ruby"
$_ = ' > Python'

Извежда следното:

$_ is now "Ruby"
$_ is now " > Python"

Интроспекция

Code smell!

Въпроси