I use rails console
a lot for poking around at models. Exploratory style. A LOT.
I always have seeded data, and typing User.find_by(slug: 'administrator')
or User.friendly.find('administrator')
gets really annoying.
This shit gets ridiculous in a REPL environment:
c = Chat.for_two(User.find_by(slug: 'mike-owens'),
User.find_by(slug: 'bob-barker'))
And of course, after you've typed that off-the-cuff, you realize you did need a reference to one of the now-anonymous users:
c.messages.create(author: User.find_by(slug: 'mike-owens'),
body: 'fuck, thats repetitive')
After a while, you get in the habit of:
mike = User.find_by(slug: 'mike-owens')
bob = User.find_by(slug: 'bob-barker')
c = Chat.for_two(mike, bob)
c.messages.create(author: mike, body: 'still repetitive')
So I've written these quick finders that get loaded into console sessions. I get to now use syntax like so:
c = Chat.for_two(U.mike, U.bob)
c.messages.create(author: U.mike, body: 'so refreshing')
If converts method names on the cleverly-short-named finder class to ActiveRecord lookups. Awesome.
It also does some tricks with wildcards: Leading or trailing underscores in the method name mark the position of a wildcard. So if you have a Location
record that looks like:
+-----+------+-------+--------------------------------------+
| id | type | name | slug |
+-----+------+-------+--------------------------------------+
| 161 | Unit | 1292B | trollingwood-hills-building-29-1292b |
+-----+------+-------+--------------------------------------+
You could have a Location
finder named L
and get it by: L._1292b
. Or use L._1292_
to get the first record where the slug contains 1292
.
Adding a ?
to the end of a method turns it into an exists?
query.
To load a file into only a console session, you'll need something like this in config/application.rb
module YourApp
class Application < Rails::Application
# ... normal configuration stuff ...
console do
ARGV.push '-r', Rails.application.root.join('lib/console.rb')
end
end
end
I think Rails should do that by default, and leave an empty lib/console.rb
ready to hack on. Check out my lib/console.rb
that defines these finders.
MIT licensed.