named_scope dependencies via returning anonymous scopes from class methods
Update: This doesn’t actually quite work, as it can override some scopes when composed. I haven’t quite figured out yet, if the technique is salvageable in some situations, or if it is always unsafe to use for chaining scopes.
I have not been able to find any info on ways to make rails named_scopes call each other, or otherwise handle dependencies. This can come up, for instance, if you have complex scopes that require joins. You might have some scopes that share the same needed set of joins to be valid, and you would like to spin that join out to a separate scope, so they could share it. Or it might be called from a has_many :through, where that join will already be valid, but alternatively called directly, where the qualified column name suddenly won’t make sense (‘other_table.column_name’ will be incorrrect in the unjoined query).
The best solution I have found is to use a class method that returns an anonymous scope. This is a contrived example that could be better handled through the has_many side of the relationship, but with sufficiently complex multi-level has_many :throughs you can easily come up with a situation where you want dependent named_scopes.
class Book
named_scope :author_join, :joins => 'INNER JOIN authors ON books.author_id = authors.id, order => 'authors.last_name, authors.first_name'
named_scope :published, :conditions => {:published => true}
def by_author_country(country_code)
Book.author_join.scoped(:conditions => ['authors.country_code = ?', country_code])
end
end
#yes they are still composable
Book.by_author_country('EU').published
Just beware that currently scopes don’t merge joins, so you can only have one joins per set of composed scopes.
Rails 2.1 and "RangeError: memory address is a recycled object" errors when running tests
require 'thread'
in a library at work, that will run without it, quieted the tests, so it’s possible even just requiring it will cause problems in Rails 2.1 (using ruby 1.8.6 p114).
Which is odd, since thread is required at least one place in the AR code itself, and elsewhere in our app. Maybe it’s an interplay of a couple libraries together, such as the non-threadsafe ‘aws/s3’ and thread?
Block form of gsub - passing backreferences to parsing functions
def hello(message)
"#{messsage}!"
end
"1234foo4567foo".gsub /(\d*)foo/, hello($1)
=> "!!"
"1234foo4567foo".gsub /(\d*)foo/, hello($1)
=> "4567!4567!"
I needed to pass a backreference ($1 or \1) from a regexp into a parsing method and then replace the match with the result. I tried many ways and couldn’t quite figure out why I couldn’t do it, before realizing that the $n variables get populated based on the last match, so won’t be populated when passed into the method call in the substitution param, or will be populated from the last time it was run. And the ’\1’ for won’t work for similar, if slightly different reasons.
Then I discovered the block form of gsub, which passes in each match to the block, and populates all the relevant regexp backreference/match globals:
"1234foo4567foo".gsub(/(\d*)foo/){|m| hello($1)}
=> "1234!4567!"
Rails 2 foxy fixtures and named_scope/has_finder closure issues
has_finder :all_active, { :conditions => {:status_id => Status.active_ids} }
This work in production, where the ids don’t change, but since we are using the newer fixture approach on this model the ids are created dynamically. Given how fixtures load, the table will probably be populated with the old values, at parse time for that class, then the test will run, and the fixtures will reload, and they will not match anymore.
This is easily fixed, when you realize what is happening:
has_finder :all_active, lambda {|| { :conditions => {:status_id => OtherModel.active_ids} }}
Blog back up after some hiccups moving to Dreamhost PS 3
I’ve spent plenty of time kvetching about problems running my Typo blog on Dreamhost. I acknowledge, though, that despite some of DH’s other hiccups, the core problem is that running Rails, on Apache fcgi, on a shared host is a Bad Idea. And while I can handle the initial set-up of a slice/VPS I don’t want to deal with the maintenance. And I don’t want to pay an arm and a leg for a fully managed set-up, just to host small sites like blog.
So when my site started going down constantly, again, due to processing getting killed for being over the memory limit, most likely, I decided I would try out Dreamhost’s new “Private Server” offering, which is sort of a managed pseudo-VPS: cheaper than a true VPS, no root, they manage everything, but you do get virtualized/dedicated resources. Sounds perfect for what I need.
Unfortunately, there is a waiting list… and my site is down now! So I decide to email support and say, hey, I’ve sent some business their way over the years, my site is down now, any way to bump me to the front of the list. Well they did – but apparently side-stepping their usual processes. I show as still wait-listed in their web, panel, but all the sites go down on my account, all of a sudden, from the switch. It turns out they have moved me over to the PS, but the DNS didn’t get updated correspondingly for all my domains.
After a day or so of wrangling with their support queue, Jason got things fixed and it seems to be working. Now I just need to see how well it works for my needs. I’m going to just stick with the Apache fcgi, for now, because it works, I’m curious how the fcgi performs when not constantly being killed for exceeding the shared allowance of memory, and Dreamhost’s proxy set-up proxies you to a single mongrel by default, so I’d need to set-up up something like nginx to proxy to my mongrel clusters, and then keep all those up myself. Not that big a deal, but I am going to run with the out of the box experience a bit first, and see how little admin work I can do.
Man, I wish I had known about this snippet earlier 1
as it would have made plenty of tooling around exploring (and even a job interview) easier. It’s much nicer than just sorting the whole mess after you decide it would take less time to find what you want then implement this very functionality.
# List instance methods without ancestor methods
String.instance_methods(false)
Mountain West Ruby Conference : day two afternoon
What To Do when Mongrel Stops Responding to Your Requests and Ruby Doesn’t Want to Tell You About It – Philippe Hanrigou
Collar mikes are fucking loud if you hold them in your hand and talk right into them. The sound guy should tweak things a bit, but still, they are definitely designed for high gain and really easy to spike.
Lots of Star Ward humor, again, and again.
Keep mongrels running via your OS tools. If there is a problem, it’s never mongrel apparently – it can be rails, your code, your db, etc. just not mongrel. I guess props to Zed, eh?
Server Admin peeps here say they learned a ton from his book. This continues to prove I don’t want to do SA for personal stuff. Maybe I will apply for Dreamhost PS (basically affordable managed VPS), after all.
gdb and dtrace (and thus D)
Lightning Talks
- gem_installer – much look at for at work, since I keep adding gems. :D
- xmpp (jabber) ruby bot (twitter signs)
- couchdb stuff about async datastore
- Ruby golfed duck ascii art. Ruby can look like perl
- RubyCocoa
- IO
- All sorts of fixtures alternatives, such as ObjectMother, scenarios builders, etc
Mountain West Ruby Conference : day two midday
Ruby Internals – Patrick Farley
This talk is actually the hard-core internals as advertised. Dig up the slides and prepare for some C. Well presented, though. Nice object-graphs/diagrams. Might be worth listening to the video, not just the slides if you are interested, as he seems to explain well. Lots of Star Wars slides/humor. Seems to be a theme since Giles’ Darth Vader/sombrero slide (note to DHS: Sith Lords could be sneaking across our unsecured border)
BDD with Shoulda – Tammer Saleh
General BDD soft sell followed with same for Shoulda – one line of spec for one line of code. Argument for testing AR association as such, not testing what they do. Overmocking – still haven’t found a good answer myself. I do agree that nested contexts help.
Related: got into debate about mocking/whitebox/glassbox/inside-of-contract vs. non-mocked/blackbox/outside-of-contract testing. I am firming up my thoughts on having both and calling them “unit” and “functional” specs/tests. During refactor functionals must pass and you rewrite units as the BDD process for your refactor. Rando (in conf irc, no idea who) seemed to follow similar practice, which is the first non-PDI response I have gotten.
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.

Articles via rss or email