/
object.rb
207 lines (177 loc) · 4.24 KB
/
object.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
class Object
#
# Return a hash of local variables in the caller's scope: {:variable_name=>value}
#
def locals
require 'binding_of_caller'
caller = binding.of_caller(1)
vars = caller.eval("local_variables").reject{|e| e[/^_/]}
vals = caller.eval("[ #{vars.join(",")} ]")
Hash[ vars.zip(vals) ]
end
def write_to(file)
open(file, "wb") { |f| f.write self.to_s }
end
#
# Gives you a copy of the object with its attributes changed to whatever was
# passed in the options hash.
#
# Example:
# >> cookie = Cookie.new(:size=>10, :chips=>200)
# => #<Cookie:0xffffffe @size=10, @chips=200>
# >> cookie.with(:chips=>50)
# => #<Cookie:0xfffffff @size=10, @chips=50>
#
# (All this method does is dup the object, then call "key=(value)" for each
# key/value in the options hash.)
#
# == BONUS FEATURE! ==
#
# If you supply a block, it just gives you the object, and
# returns whatever your block returns.
#
# Example:
# >> {a: 10, b: 2}.with { |hash| hash[:a] / hash[:b] }
# => 5
#
# Good for chaining lots of operations together in a REPL.
#
def with(**options)
if block_given?
yield self
else
obj = dup
options.each { |key, value| obj.send "#{key}=", value }
obj
end
end
#
# Creates attr_accessors and an initialize method
# that accepts the attrs as arguments.
# (It's kinda like an inline version of Struct.new(*args))
#
def self.attrs(*names)
attr_accessor *names
define_method :initialize do |*vals|
names.zip(vals) do |name, val|
instance_variable_set("@#{name}", val)
end
end
end
#
# Serialize this object to a binary String, using Marshal.dump.
#
def marshal
Marshal.dump self
end
alias_method :to_marshal, :marshal
#
# Serialize this object to YAML.
#
def to_yaml
YAML::dump(self)
end
#
# Serialize this object to JSON (defaults to "pretty" indented JSON).
#
def to_json(pretty=true)
pretty ? JSON::pretty_generate(self) : JSON.dump(self)
end
#
# Emit a quick debug message (only if $DEBUG is true)
#
def dmsg(msg)
if $DEBUG
case msg
when String
puts msg
else
puts msg.inspect
end
end
end
#
# Time a block.
#
def time(message=nil)
start = Time.now
result = yield
elapsed = Time.now - start
print "[#{message}] " if message
puts "elapsed time: %0.5fs" % elapsed
result
end
#
# Quick and easy benchmark.
#
# Examples:
# bench { something }
# bench(90000000) { something }
# bench :fast => proc { fast_method }, :slow => proc { slow_method }
#
# In Ruby 1.9:
# bench fast: ->{ fast_method }, slow: ->{ slow_method }
#
def bench(*args, &block)
# Shitty perl-esque hack to let the method take all the different kind of arguments.
opts = Hash === args.last ? args.pop : {}
n = args.first || 100
if opts.any?
raise "Error: Supply either a do/end block, or procs as options. Not both." if block_given?
raise "Error: Options must be procs." unless opts.all? { |k, v| v.is_a?(Proc) }
benchblock = proc do |bm|
opts.each do |name, blk|
bm.report(name.to_s) { n.times &blk }
end
end
elsif block_given?
benchblock = proc do |bm|
bm.report { n.times &block }
end
else
raise "Error: Must supply some code to benchmark."
end
puts "* Benchmarking #{n} iterations..."
Benchmark.bmbm(&benchblock)
end
def present?
true
end
#
# Negates a boolean, chained-method style.
#
# Example:
# >> 10.even?
# => true
# >> 10.not.even?
# => false
#
def not
NotWrapper.new(self)
end
#
# Serialize this object to a Python bencoded (pickled) string
#
def to_bencode
BEncode.dump(self)
end
end
class NotWrapper < BasicObject # :nodoc:
def initialize(orig)
@orig = orig
end
def inspect
"{NOT #{@orig.inspect}}"
end
def is_a?(other)
other === self
end
def method_missing(meth, *args, &block)
result = @orig.send(meth, *args, &block)
if result.is_a? ::TrueClass or result.is_a? ::FalseClass
!result
else
raise "Sorry, I don't know how to invert #{result.inspect}"
end
end
end