Skip to content

Instantly share code, notes, and snippets.

@apeiros
apeiros / class_callings.rb
Last active December 22, 2015 11:19
class_* convenience variants
class Object
def class_call(*args, &block)
self.class.__send__(caller_locations(1,1).first.label, *args, &block)
end
def class_method(name=caller_locations(1,1).first.label)
self.class.method(name)
end
def class_send(name=caller_locations(1,1).first.label, *args, &block)
self.class.__send__(name, *args, &block)
end
class Object
def class_call(*args, &block)
self.class.__send__(caller_locations(1,1).first.label, *args, &block)
end
end
class Foo
def self.bar
"bar"
end
module A
X = 1
end
module A
class B
def self.x
X
end
end
end
## file a.rb
module A
X = 1
end
## file a/b.rb
module A
class B
def self.x
X
class String
def match_all(regex)
if block_given?
scan(regex) { yield $~ }
else
enum_for(:scan, regex).map { $~ }
end
end
end
@apeiros
apeiros / ruby_string_scrubbed_utf_8.rb
Last active December 18, 2015 07:39
Clean a string from invalid byte sequences.
class String
# Defaults for String#scrubbed_utf8's options argument
ScrubbedUtf8Defaults = {invalid: :replace, undef: :replace}
# Similar to what String#encode does, the options argument is also the same,
# but it defaults to :replace for both :invalid and :undef options.
#
# :invalid:
# If the value is :replace, #encode replaces invalid byte sequences in str
# with the replacement character. The default is :replace.
@apeiros
apeiros / part_of_irbrc.rb
Created May 7, 2013 17:25
Enter passwords in pry/irb without echo
require 'io/console' # requires ruby 1.9.3
module PasswordString
def inspect; "[PASSWORD]"; end
def to_s; "[PASSWORD]"; end
def dup; obj=super;obj.extend PasswordString; obj; end
def clone; obj=super;obj.extend PasswordString; obj; end
end
def password
require 'yaml'
class Configuration
def self.load_yaml(file)
new(YAML.load_file(file))
end
def initialize(config, schema=nil)
config.each do |key, value|
value = Configuration.new(value) if value.is_a?(Hash)
def Object.create(attrs)
obj = new
obj.singleton_class.send(:attr_accessor, *attrs.keys)
attrs.each do |name,value| obj.instance_variable_set(name.to_s.sub(/\A@?/, '@'), value) end
obj
end
o = Object.create(foo: 12, bar: "hi") # => #<Object:0x007fc53a0f7bc8 @bar="hi", @foo=12>
o.bar # => "hi"
# encoding: utf-8
require 'sorting/ascending'
require 'sorting/descending'
module Sorting