How do I log queries in a rake task using datamapper and padrino? - ruby

I have a padrino install that is using datamapper and logging queries to a file. This is working fine when browsing my application. But queries are not logged if executed inside a rake file. Why?
This is how the task is defined:
# lib/tasks/example.rake
task :example => :environment do
players = Player.all #Player is a datamapper object
puts players.first.to_s
end
I also added this line to /config/boot.rb
Padrino::Logger::Config[:development] = { :log_level => :devel, :stream => :to_file }
And this line is called in /config/database.rb
DataMapper.logger = logger
And this is how I'm executing the script
$ padrino rake example

Invoke rake with:
PADRINO_LOG_LEVEL=development padrino rake my:task

Related

Can Rake run each test in a separate Ruby instance?

I have a very simple Rakefile to test a small Ruby gem. It looks like this:
Rake::TestTask.new
task :default => :test
It invokes two tests that define constants with the same name. This results in errors being output by the second test like this:
warning: already initialized constant xxxxx
The reason for this is because Rake executes all of the tests within a single Ruby instance:
/usr/bin/ruby -I"lib" -I"/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib" "/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/rake_test_loader.rb" "test/test*.rb"
How should I specify that each test should be run in a separate Ruby instance ?
I have achieved this as shown below but I wonder if there is a better way because this solution doesn't scale well for lots of tests.
Rake::TestTask.new(:one) { |t| t.test_files = %w(test/test_one.rb) }
Rake::TestTask.new(:two) { |t| t.test_files = %w(test/test_two.rb) }
task :default => [:one, :two]
Instead of using Rake::TestTask, you could define a test task in your Rakefile that loops through each test file and runs them with sh like this:
task :test do
libs = ['lib',
'/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib',
'/usr/lib/ruby/gems/2.1.0/gems/rake-10.3.2/lib/rake/rake_test_loader.rb']
test_files = FileList['test/**/test*.rb']
test_files.each do |test_file|
includes = libs.map { |l| "-I#{l}"}.join ' '
sh "ruby #{includes} #{test_file}"
end
end

How do I programmatically extract a rake task's description?

I'm attempting to capture the equivalent of rake -D programmatically. I can load the Rakefile I'm targeting and see a list of tasks, but I can not figure out how to get the descriptions.
This will let me see the tasks that I am interested in:
Dir.chdir #myTarget
rake = Rake::Application.new
Rake.application = rake
rake.init
rake.load_rakefile
tasks = Rake.application.tasks
puts tasks.inspect
The above outputs something similar to:
[<Rake::Task default => [test]>, <Rake::Task foodcritic => []>, <Rake::Task integration => [kitchen:all]>]
My question is how to access the desc comments that are visible if I run rake -D. Here's what I'm after:
rake foodcritic
Run Foodcritic lint checks
rake integration
Alias for kitchen:all
rake kitchen:all
Run all test instances
Here's the final solution. The key was that I was missing metadata from the taskmanager:
Dir.chdir #myTarget
rake = Rake::Application.new
Rake::TaskManager.record_task_metadata = true
Rake.application = rake
rake.init
rake.load_rakefile
Rake.application.tasks.each do |t, n|
puts t
puts t.full_comment
puts "\n"
end
Use the methods comment or full_comment for that. More docs on the Rake::Task class here.

How to create an RSpec Rake task using RSpec::Core::RakeTask?

How do I initialize an RSpec Rake task using RSpec::Core::RakeTask?
require 'rspec/core/rake_task'
RSpec::Core::RakeTask.new do |t|
# what do I put in here?
end
The Initialize function documented at
http://rubydoc.info/github/rspec/rspec-core/RSpec/Core/RakeTask#initialize-instance_method isn't very well-documented; it just says:
- (RakeTask) initialize(*args, &task_block)
A new instance of RakeTask
What should I put for *args and &task_block?
I'm following in the footsteps of someone who had already started to build some ruby automation for a PHP project using RSpec in combination with Rake. I'm used to using RSpec without Rake, so I'm unfamiliar with the syntax.
Thanks,
-Kevin
Here is an example of my Rakefile:
require 'rspec/core/rake_task'
task :default => [:spec]
desc "Run the specs."
RSpec::Core::RakeTask.new do |t|
t.pattern = "spec.rb"
end
desc "Run the specs whenever a relevant file changes."
task :watch do
system "watchr watch.rb"
end
This allows to run specs defined in the spec.rb file from Rake
This is what my rakefile looks like
gem 'rspec', '~>3'
require 'rspec/core/rake_task'
task :default => :spec
desc "run tests for this app"
RSpec::Core::RakeTask.new do |task|
test_dir = Rake.application.original_dir
task.pattern = "#{test_dir}/*_spec.rb"
task.rspec_opts = [ "-I#{test_dir}", "-I#{test_dir}/source", '-f documentation', '-r ./rspec_config']
task.verbose = false
end
You can 'rake' from your tests directory and it will run all tests with a name [something]_spec.rb - and it should work across different test directories (e.g. different projects); if you have source in a separate directory (e.g. in the code above, a subdirectory called '/source' it will pick them up. Obviously, you can change that source directory to what you want.
Here's the rspec_config file I use - you can add your own settings in here:
RSpec.configure do |c|
c.fail_fast = true
c.color = true
end

Generate migrations outside Rails

I'm using ActiveRecord outside Rails. I would want a program to generate the skeleton of a migration ( as well as a system to collect and maintain them ).
Can anyone make a suggestion?
Also take a look at new active_record_migrations
There is a gem to use Rails Database Migrations in non Rails projects. Its name is "standalone_migrations"
Here is a link
https://github.com/thuss/standalone-migrations
If you do not like to use rake, but still get the system part of ActiveRecord::Migration, then you can use the following to handle the ups and downs from plain ruby (without any rails):
require 'active_record'
require 'benchmark'
# Migration method, which does not uses files in db/migrate but in-memory migrations
# Based on ActiveRecord::Migrator::migrate
def migrate(migrations, target_version = nil)
direction = case
when target_version.nil?
:up
when (ActiveRecord::Migrator::current_version == target_version)
return # do nothing
when ActiveRecord::Migrator::current_version > target_version
:down
else
:up
end
ActiveRecord::Migrator.new(direction, migrations, target_version).migrate
puts "Current version: #{ActiveRecord::Migrator::current_version}"
end
# MigrationProxy deals with loading Migrations from files, we reuse it
# to create instances of the migration classes we provide
class MigrationClassProxy < ActiveRecord::MigrationProxy
def initialize(migrationClass, version)
super(migrationClass.name, version, nil, nil)
#migrationClass = migrationClass
end
def mtime
0
end
def load_migration
#migrationClass.new(name, version)
end
end
# Hash of all our migrations
migrations = {
2016_08_09_2013_00 =>
class CreateSolutionTable < ActiveRecord::Migration[5.0]
def change
create_table :solution_submissions do |t|
t.string :problem_hash, index: true
t.string :solution_hash, index: true
t.float :resemblance
t.timestamps
end
end
self # Necessary to get the class instance into the hash!
end,
2016_08_09_2014_16 =>
class CreateProductFields < ActiveRecord::Migration[5.0]
# ...
self
end
}.map { |key,value| MigrationClassProxy.new(value, key) }
ActiveRecord::Base.establish_connection(
:adapter => 'sqlite3',
:database => 'XXX.db'
)
# Play all migrations (rake db:migrate)
migrate(migrations, migrations.last.version)
# ... or undo them (rake db:migrate VERSION=0)
migrate(migrations, 0)
class ApplicationRecord < ActiveRecord::Base
self.abstract_class = true
end
class SolutionSubmission < ApplicationRecord
end
I have made a minimal example of how to use active record outside of Rails. Rails migrations (Standalone migrations) in non-Rails (and non Ruby) projects.
https://github.com/euclid1990/rails-migration
(Support Rails >= 5.2)
You can refer Rake file in this repo.
There is another gem called otr-activerecord. This gem provides following tasks:
rake db:create
rake db:create_migration[name]
rake db:drop
rake db:environment:set
rake db:fixtures:load
rake db:migrate
rake db:migrate:status
rake db:rollback
rake db:schema:cache:clear
rake db:schema:cache:dump
rake db:schema:dump
rake db:schema:load
rake db:seed
rake db:setup
rake db:structure:dump
rake db:structure:load
rake db:version
All you need to do is to install it and add a Rakefile with content
load 'tasks/otr-activerecord.rake'
OTR::ActiveRecord.configure_from_file! 'config/database.yml'
I prefer this gem over active_record_migrations or Standalone Migration because those two gems depend on railties, which is almost the entire Rails. For example, Nokogiri takes a long time to compile, and takes a lot of spaces.

Build extension spree e-commerce

I'm with one problem when executed the step 5.7. In my extension not metting the path:
#lib/spree/flag_promotion_configuration.rb.
I must create the directory 'spree' and after create the file 'flag_promotion_configuration.rb' ?
If I write this in the file, as the tutorial required:
#lib/spree_flag_promotions/engine.rb
module Spree::ActiveShipping; end
....
module SpreeFlagPromotions
class Engine < Rails::Engine
initializer "spree.flag_promotions.preferences", :after => "spree.environment" do |app|
Spree::FlagPromotions::Config = Spree::FlagPromotionConfiguration.new
end
....
end
end
And I executed:
$ rake db:migrate
Return this error:
rake aborted!
uninitialized constant Spree::FlagPromotions
Tasks: TOP => db:migrate => environment
(See full trace by running task with --trace)
I believe it has anything to do with:
#lib/spree/flag_promotion_configuration.rb.
Because they do not know where to create this file is or where.

Resources