Upgrade to Pro — share decks privately, control downloads, hide ads and more …

[Wroc_Love.rb 2018] [Lightning Talk] To refine or not to refine

[Wroc_Love.rb 2018] [Lightning Talk] To refine or not to refine

Vladimir Dementyev

March 18, 2018
Tweet

More Decks by Vladimir Dementyev

Other Decks in Programming

Transcript

  1. “Developed my Matz’s boss, Shugo” “Initially was more powerful but

    JRuby…" "Koichi Sasada wants to remove Refinements” http://rubynoname.ru/posts/2017/S08E08.html *2016
  2. DEPENDENCY REDUCTION module Anyway ::HashExt refine Hash do def stringify_keys!

    keys.each do |key| val = delete(key) val.stringify_keys! if val.is_a?(Hash) self[key.to_s] = val end end end end https://github.com/palkan/anyway_config
  3. class Anyway ::Config using Anyway ::Ext ::DeepDup using Anyway ::Ext

    ::Hash def self.attr_config(*args, **hargs) @defaults = hargs.deep_dup defaults.stringify_keys! @config_attributes = args + defaults.keys attr_accessor(*@config_attributes) end end https://github.com/palkan/anyway_config DEPENDENCY REDUCTION
  4. MODERNIZATION module ThreadFetch # Thread.fetch is only available since 2.5

    refine Thread do def fetch(key, fallback = : __undef __) raise KeyError, "key not found: #{key}" if !key?(key) && fallback == : __undef __ self[key] || fallback end end end https://github.com/palkan/isolator
  5. PERFECT PRIVACY if Array.instance_methods(false).include?(:sum) && !(%w[a].sum rescue false) # Using

    Refinements here in # order not to expose our internal method using Module.new { refine Array do alias :orig_sum :sum end } #… end https://github.com/rails/rails/pull/27363/files
  6. to_proc https://github.com/palkan/clowne # Add to_proc method for lambda module LambdaAsProc

    refine Proc do def to_proc return self unless lambda? this = self proc { |*args| this.call(*args.take(this.arity)) } end end end
  7. SYNTAX SUGAR https://github.com/palkan/test-prof using FloatDuration using StringStripHeredoc msg = <<-MSG.strip_heredoc

    EventProf results for #{@profiler.event} Total time: #{@profiler.total_time.duration} MSG
  8. #PROTIP module Json refine Integer do def to_json to_s end

    end end using Json p Module.used_modules # => [Json]
  9. PROBLEMS module Json refine Integer do def to_json to_s end

    end end using Json p 1.send(:to_json) # => "1" p 1.public_send(:to_json) # => NoMethodError