Here is an ongoing collection of weird Ruby snippets that I have come across in my travels.
Camping R Helper
Camping uses a bizarre helper method R that acts as a stand-in for a parent class.
class Edit < R '/post/(\d+)/edit'
def get(post_id)
require_login!
@post = Post.find(post_id)
render :edit
end
# ...
See: https://github.com/camping/camping/blob/main/examples/blog.rb#L63
Decoding the implementation of this method left as an exercise for the reader… notably grep(Hash), gsub(CampTools.descape){$1}, and the h.any??.
def R(c,*g)
p,h=/\(.+?\)/,g.grep(Hash)
g-=h
raise "bad route" if !u = c.urls.find{|x|
break x if x.scan(p).size == g.size &&
/^#{x}\/?$/ =~ (x=g.inject(x){|x,a|
x.sub p,U.escape((a.to_param rescue a))}.gsub(CampTools.descape){$1})
}
h.any?? u+"?"+U.build_query(h[0]) : u
end
There is also this gem: (https://github.com/camping/camping/commit/6724a04b37902c48c44c568ec5ce53b2f1a28620)
class Object
def meta_def(m,&b)
(class<<self;self end).instance_eval{define_method(m,&b)}
end
end
Later on in the camping/reststop library, we ammend the afforementioned R method with an even fancier REST method, featuring an all caps method name, a module_eval, a meta_def, and an all caps global.
def REST(r, options = {})
crud = R "#{options[:prefix]}/#{r}/([0-9a-zA-Z]+)/([a-z_]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}/([0-9a-zA-Z]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}/([a-z_]+)(?:\.[a-z]+)?",
"#{options[:prefix]}/#{r}(?:\.[a-z]+)?"
crud.module_eval do
meta_def(:restful?){true}
$LOG.debug("Creating RESTful controller for #{r.inspect} using Reststop #{'pull version number here'}") if $LOG
def get(id_or_custom_action = nil, custom_action = nil) # :nodoc:
# ...
WEBrick Method Names
The WEBrick HTTP server toolkit provides a way to implement custom behavior through the use of mounted ‘servlets’, which have funny looking method names (def do_GET).
class Simple < WEBrick::HTTPServlet::AbstractServlet
def do_GET request, response
status, content_type, body = do_stuff_with request
response.status = 200
response['Content-Type'] = 'text/plain'
response.body = 'Hello, World!'
end
end
See: https://github.com/ruby/webrick/blob/master/lib/webrick.rb
WEBrick Option Symbols
It’s not that unusual to see capital letters in symbols, but this line from the documentation alwasy strikes me as odd. Perhaps its just because of the hashrocket syntax…
server = WEBrick::HTTPServer.new :Port => 8000, :DocumentRoot => root
Syntropy Example
syntropy is a web framework for building multi-page and single-page apps. I’m no what this example does, but its cool looking:
export template {
div {
markdown <<~MD
```ruby
@buffer << #{foo}
```
MD
}
}.tap { puts '!' * 40; puts Papercraft.compiled_code(it.proc); puts}
See: https://github.com/digital-fabric/syntropy/blob/main/examples/bad.rb