Mountain West Ruby Conference : day two morning 1
Enough Statistics so that Zed won’t yell at you – Devlin Daley
Reminds me how horrible our whole society is about the basics of stats and probabilities. I think our overly trained ability to pick out patterns really hurts us. At least it’s not just programmers who are clueless about stats – it’s just more surprising because they are technically proficient and assumed to be intelligent and educated in math. Good survey lecture for what programmers should know before thinking about doing any benchmarking.
Next Generation Data Storage with CouchDB – Jay Lehnardt
Why is everyone hating on RDBs. ;) Cool talk – already read a lot about CouchDB, though. Do like the focus on some of the whys for parallelization/map-reducing. Hmmm, couchdb as the git of data. I would follow it closer, if I had a use anywhere on the horizon. I figure by the time I get around to using it the nitty gritties might have changed (especially usage and client libraries)
Mountain West Ruby Conference : day one notes
Evan Phoenix opening keynote (how Rubinius is run)
Highlights low barrier of entry for developers as theme
- Anti-core/elite group – creates unhealthy environment (reminds me of how getting a patch applied for merb on github was)
- Spec suite makes good entryway
Talking about ruby community in general
- Niceness
- Excitability/early adopterism
- again, see slideshow for highlights
- A little polyanna (I don’t think so, but it got mentioned)?
- very gitty bazaar style (gack, typo NOT cathedral)
- a lot of subtle “drawing contrasts” with rails
My sorta hippie.
My thoughts on question?: ease of contributing, github as singularity, loved it all, but self-selecting elitism by cutting edgeness, does it scale? How do you keep openeness as project grows – see mailinglist overwhelmed with help vampires after rails got popular. Also see back-channels
A: Roughly: organically. Create the excitement and environment and the pool of people to handle the growth will come online as it grows.
Ezra’s half
Don’t be overly clever. Really most of his talk is about that and being a responsible coder if you are making a library. And a reminder that avoiding premature optimization doesn’t mean avoiding all optimization
- Good explanation of event-driven (thin, even mongrel) versus threaded server (mongrel)
- Rack sidestepping of framework is sexy
- Provides is the best feature, still. Action-args is close. Picking a favorite child.
My thought: what about elegance/clever usages getting mainstreamed into the interpretor. Refactor then, I assume? To simple to bother asking. Mongrel + evented mongrel? A: yes, if needed Magic of action args countered by increasing client-code explicitness
Giles talk
I read enough of it on blogs, and aside from that it’s a little crazy. Giles is quite interesting in person. I think his shown code may be a little unneccessaily “meta.” He’s keeping mum if that is an ironic by intent thingWycats:
DM Rocks, that is all. Also awesome transitions in slides.
Didn’t take notes for rest.
I think Evan’s talk was the best part. The technical talks you can pick up from the slides, but the more overviewy touchy-feely part is hard to get except in person. Everyone rocks, but I really liked Evan’s talk.
Calling (invoking) rails rake tasks from within ruby, for testing, try 2
Yesterday I wrote a post on capturing the output of rake from a ruby call using backticks, because I wanted to do so in a test. Well, I had Date.today stubbed out, but got lazy and used yesterday’s date, so of course when I come in today the test fails. In the light of a new day my problem was obvious. If you call rake from a sub-shell, say via ``, of course your mocking will not exist in that process. So today, I had Another Wonderful Opportunity for Learning (there are acronyms for this that use a different word than wonderful): a chance to do it right.
It took a little digging to figure out how to get this to work right with the built-in rails tasks, so here you go:
require 'rake'
require 'rake/rdoctask'
require 'rake/testtask'
require 'tasks/rails'
def capture_stdout
s = StringIO.new
oldstdout = $stdout
$stdout = s
yield
s.string
ensure
$stdout = oldstdout
end
Rake.application.rake_require '../../lib/tasks/metric_fetcher'
results = capture_stdout {Rake.application['metric_fetcher'].invoke}
I liberated capture_stdout from the rake tests themselves. In retrospect, I should have just looked there first. As TDD and especially BDD get even more widespread the tests are often the easiest place to look for good examples of usage.
Capturing a system call in ruby with backticks, while setting an environment variable 1
As you may know system() and `` both make system calls in ruby, but the second one captures the STDOUT for you, essentially, which is handy sometimes, like when testing. They don’t necessarily both do this by just a straight call to the commandline, but various internal utilities that make such thing possible in Windows too, for instance.
Well the problem with this is it can mess with your setting of an ENV as a precursor to your command. For instance, this is valid on my platform:
RAILS_ENV=test rake metric_fetcher
and works via system():
system("RAILS_ENV=test rake metric_fetcher")
but chokes in backticks, probably due to the aforementioned jiggering around for Windows compat:
`RAILS_ENV=test rake metric_fetcher`
Now you generally can just move the command back to the beginning of the line:
`rake RAILS_ENV=test metric_fetcher`
but if for some bizarre reason that doesn’t work for you (it’s probably something else going, wrong, though, to be honest) you can do this:
ENV['RAILS_ENV']='test'; `rake metric_fetcher`
So ultimately, I can do this hacky wonder:
assert `rake RAILS_ENV=test metric_fetcher`.empty?
if my rake task succeeds silently and fails noisily (which is a useful characteristic for cron’ed tasks).
Thanks to Defiler and ocotpod for proving to me I really did have my head up my ass and that all but the leading env var in backticks form should work as expected.(fixture set-up issues as usual).
Addendum And if you are calling rake like this in a test and getting odd problems – consider turning transaction fixtures off.
Isolated controller and view testing in merb 2
As part of learning rspec for blerb, I’m working on better mocking for truer isolation tests. This includes true unit tests for models, controllers, and views, unlike the rails/testunit standard approach. This involves, primarily, mocking out the models and turning rendering off for the controller testing, and figuring out how to test just the rendering without the rest of the stack, for the views. I won’t claim any of this is well organized, or finalized, as we are just figuring out how to do some of it in the first place, but feel free to crib any of this you like off the git-web for blerb.
First a controller
describe "Articles Controller", "index action" do
before(:each) do
@article1 = mock("article")
@article2 = mock("article")
@articles = [@article1, @article2]
Article.should_receive(:all).and_return(@articles)
@controller = Articles.build(fake_request)
@controller.stub!(:render)
@controller.dispatch('index')
end
it "should get successfully" do
@controller.status.should == 200
end
it "should assign all articles" do
@controller.instance_variable_get("@articles").should == @articles
end
end
The one non-intuitive part (for me), was making sure to stub render – otherwise you’ll be calling the view, and getting errors on your mocks because the view is calling methods you didn’t mock/stub out. Thus, it is key to isolate the controller from the model and the view if you want to easily test it, in this style. Oh yeah, and knowing about fake_request as part of the merb testing help.
The slightly trickier part was doing the same for the views. I dug through the merb source, and got most of the way, but hadn’t figured out how to pass in assigned instance variables by creating a dummy ViewContext, when ezra gave me a hand. I would NOT (and will not long term) do it exactly like this, but rather extract some sort of spec_helper to wrap the fake view_context creation and template engine calls, but it’s useful as is for an illustrative example.
class FakeArticleController
def initialize(articles)
@articles = articles
end
end
describe "/articles" do
before(:each) do
@article1 = mock("article")
@article2 = mock("article")
@article1.should_receive(:title).and_return("Article 1")
@article2.should_receive(:title).and_return("Article 2")
Article.stub!(:all).and_return([@article1,@article2])
@template = "#{MERB_VIEW_ROOT}/articles/index.html.erb"
@engine = Merb::Template.engine_for(@template)
@fake = Merb::ViewContext.new FakeArticleController.new(Article.all)
@body = @engine.transform(:file => @template, :view_context => @fake)
end
it "should list all articles" do
@body.should include("<li>Article 1</li>")
@body.should include("<li>Article 2</li>")
end
end
utility_belt tweak 2 - passing a string directly to pastie
def pastie(string=nil)
pastie_url = Net::HTTP.post_form(URI.parse("http://pastie.caboo.se/pastes/create"),
{"paste_parser" => "ruby",
"paste[authorization]" => "burger",
"paste[body]" => (string || MacClipboard.read)}).body.match(/href="([^\"]+)"/)[1]
MacClipboard.write(pastie_url)
system("open #{pastie_url}")
pastie_url
end
If you are wondering WTF is going on, read the previous post
Textmateing a string from irb - a tweak for Gile's new gem, utility_belt
So Giles Bowkett just released a gem that does most of the tweaks I had been meaning to add to my .irbrc, but had been to lazy. utility_belt is pretty awesome, but there is one tiny tweak I wanted to add to make it optimal, and Giles isn’t known for making himself easy to get a hold of (especially now that comments seem to be perpetually closed on his blog). So instead I just hacked it on the gem myself. I’m not going to bother distributing it as a gem myself, but you are welcome to steal the idea and add it to your copy.
To be able to pass a string (say like the last result, via ”_”, when irb just dumped 500 lines of output on you) to Textmate, edit lib/interactive_editor.rb like so
10,13c10,13
< def edit
< unless @file
< @file = Tempfile.new("irb_tempfile")
< end
---
> def edit(string)
> @file = Tempfile.new("irb_tempfile")
> @file.write string
> @file.close
17a18
> @file.unlink
22c23
< def edit(editor)
---
> def edit(editor, string)
27c28
< IRB.conf[:interactive_editors][editor].edit
---
> IRB.conf[:interactive_editors][editor].edit(string)
30,31c31,32
< def vi
< edit(:vim)
---
> def vi(string=nil)
> edit(:vim,string)
34,35c35,36
< def mate
< edit(:mate)
---
> def mate(string=nil)
> edit(:mate,string)
38,39c39,40
< def emacs
< edit(:emacs)
---
> def emacs(string=nil)
> edit(:emacs,string)
Now glory in “mate _” from irb.
Or best of all: use ruby2ruby and call mate on the result of #to_ruby on a method. You can edit the method in Textmate and save, and wallah, it’s applied. Of course, getting that working correctly in an actual Module/Class hierarchy might be a bit more complicated, and I leave as an exercise for the reader.
http access to blerb via gitweb and general update.
hornbeck’s master repo is available at git://42squared.com/git/blerb. Stop by #blerb if you want to hack on it. With the help of mattly and court3nay I’ve put a copy of the repo up at git.caboo.se so now there is web access to blerb source via gitweb, for those who don’t want to brave git, yet, or who already have access to git.caboo.se (I believe it’s wide open for read-only, of course), or just those that like browsing the history/changelogs/ through a webterface. I’ll be pushing up to there every so often.
On another note, we plan on borrowing everything that makes sense to from Ezra’s earlier stab at a similar project: MrBlog
Fixing the fieldWithErrors problem on the hidden field generated by the checkbox helper: field_error_proc
#Fix problem with fieldWithErrors and the hidden field generated for a checkbox
ActionView::Base.field_error_proc = Proc.new do |html_tag, instance|
if html_tag =~ /<(input)[^>]+type=["'](hidden)/
html_tag
elsif html_tag =~ /<(input)[^>]+type=["'](checkbox|radio)/
"<div class=\"fieldWithErrors miniFieldWithErrors\">#{html_tag}</div>"
else
"<div class=\"fieldWithErrors\">#{html_tag}</div>"
end
end
This is also where you could fix the whole arbitrarily inserted div messing your layouts, as well, by replacing it with a span, say. ;)
Merb blog begun: blerb 6
It’s nowhere near being ready yet, but I made my first contributions tonight. I was going to code up one myself, but a couple other caboosers already where planning on it, and since I am somewhat time constrained on personal projects, that was perfect.
Just getting started was quite a bit to bite off, though, as it involved learning git, datamapper, merb, rspec, and how the last three all play together (like how to use rspecs built-in mocking when trying to do controller specs in merb). I got it checked out and my first minor changes specc’ed and made, and pushed back upstream, though, so it should go easier from here out.
I will post more when there is something more to say (like maybe a repo to browse, or a website, or something that is usable as a blog)
Update: The other contributor to blerb so far is John Hornbeck.

Articles via rss or email