How can I load the Middleman environment in a rake task

I’d like to be able to access the Middleman environment (specifically the sitemap for my site) in the context of a rake task. In a rails project I could do something like this:

desc "my task"
task :my_task => :environment do
  posts = blog(:blog).articles
  ...
end

How could I create an :environment task that would make this possible?

I wondered if the middleman console command would hold the answer. Looking at the source, I see that it uses Thor. Which prompts another question: would it be easier to do what I want using a Thor action instead of a rake task?

I took a closer look at the source for the middleman console command and figured something out that works:

desc 'Build a list of tags and save it to data/categories.yml'
task :dump_categories do
  require 'middleman-blog'
  @app =::Middleman::Application.server.inst
  tags = (@app.blog(:blog).tags.keys + @app.blog(:episodes).tags.keys).uniq
  File.open('data/categories.yml', 'w') do |f|
    f.write tags.to_yaml
  end
end

This approach didn’t quite work how I hoped it would, but I’ll write it down anyway.
I tried creating an environment task like this:

desc 'Load the Middleman environment'
task :environment do
  require 'middleman-blog'
  @app =::Middleman::Application.server.inst
end

I could then make my rake task load the environment:

task :dump_categories => :environment do
  tags = @app.blog(:blog).tags.keys
  # ...
end

When I launch the middleman console, I can fetch my blog tags just by running blog(:blog).tags, but inside of this rake task, I had to run @app.blog(:blog).tags. I wonder if IRB.irb(nil, @app) (source) makes this possible in the console, but I wasn’t sure how to make the same thing happen in the context of a rake task.

In the end, I decided to get rid of the :environment task and make my :dump_categories task self-contained.