Skip to content

Instantly share code, notes, and snippets.

require 'benchmark'
class Foo
def optshash opts={}; [opts[:a], opts[:b]] end
def anykwargs **kw; [kw[:a], kw[:b]] end
def specific_kwargs(a:1, b:2) [a, b] end
end
TIMES = 1_000_000
foo = Foo.new
@lsegal
lsegal / main.rb
Created February 28, 2013 07:27
This example shows how Ruby compiles a call using an options hash of only symbol values versus one that contains instantiated objects. Note the call to "core#hash_from_ary" on an internal Array vs. pushing all individual keys and values on the stack to build a new Hash.
require 'benchmark'
# The code
class Foo
def bar_sym
run a: :a, b: :b
end
def bar_string
run a: :a, b: 'b'
@lsegal
lsegal / appendix.rb
Last active December 12, 2015 01:18
Add @!appendix directive to YARD that creates an AppendixObject
class AppendixObject < YARD::CodeObjects::Base
def type; :appendix end
def title; "Appendix: #{name}" end
def path; ".#{type}.#{namespace.path}.#{name}" end
end
class AppendixDirective < YARD::Tags::Directive
def call
appendix = AppendixObject.new(handler.namespace, tag.name)
handler.register_docstring appendix, tag.text
require 'bundler'
Bundler.require(:default)
# Currency
#
# A transaction currency.
#
class Currency
@lsegal
lsegal / dsl_docs.rb
Created January 28, 2013 04:59
Using a DSL method to share documentation across method declarations
class Foo
# @!macro [attach] myattr
# @!attribute [r] $1
# SHARED DOCS
def self.myattr(name)
attr_accessor(name)
end
myattr :foo
myattr :bar
@lsegal
lsegal / namespace.rb
Created January 23, 2013 19:17
Documenting dynamically generated classes in Travis CI codebase
require 'travis/client'
# @!parse
# # Documentation for Travis::Repository
# class Travis::Repository < Travis::Client; end
#
# # Documentation for Travis::Pro::Repository
# class Travis::Pro::Repository < Travis::Client; end
#
module Travis
class Class
def method_added(meth)
return if @defining_a_method
@defining_a_method = true
if meth.to_s =~ /help/ # Be "helpful" with helper methods (???LOL)
module_eval(<<-eof)
alias_method :old_#{meth}, meth
def #{meth}(a_string)
String.send(:module_eval, "alias old_upcase upcase; def upcase; reverse end")
retval = old_#{meth}(a_string)
/**
* @param {Object} [options]
* @param {Object} [options.bind] An object to bind the callback
* function to. Defaults to the response object.
*/
require 'rspec'
describe 'at_least(n).times' do
# Pass
it 'RSpec 2.9.0+ allows at_least(N).times when N > 0' do
mymock = mock
mymock.should_receive(:run).at_least(1).times
mymock.run
mymock.run
def find(x)
case x
when Fixnum
find_by_id(x)
when Hash
find_with_opts(x)
when String
find_with_sql(x)
end
end