Few days ago I needed to migrate s3 data from one account to another account. I’ve decided to use as background worker heroku server. And wrote this code below:
Yesterday I published the simple gem for devise. Now it is easy to add ‘Login As’ functionality to your admin pages.
1. Add gem ‘devise_masquerade’ to your Gemfile.
2. Add before_filter :masquerade_user! to the application_controller.rb
3. Add link_to ‘Login As’, masquerade_path(user) to your table with users.
4. Use it :)
rails code:
class Post < ActiveRecord::Base
def method1
require 'ruby-debug'
debugger
...
end
end
In the debug session you should run the next following code:
ActiveRecord::Base.logger = Logger.new($stdout)
My ~/.rdebugrc
set autolist set autoeval set autoreload
Today I found a very interesting trick connection with aggregation functions in the ActiveRecord.
For example you have a Stat(clicks:integer(default: 0), key:string) model. And you need to find sum of the clicks for the specific key.
Stat.where(:key => 'your key').all(:select => "sum(clicks) as clicks")
Lets imagine you have the stats with key. And as result of expression you will get stat object with clicks.
[#<Stat clicks: 102>]
But if you have no the stats with key:
Stat.where(:key => 'your key').count => 0
Lets the same expression for finding summary of the clicks:
Stat.where(:key => ‘your key’).all(:select => “sum(clicks) as clicks”)
[#<Stat clicks: nil>]
As I wrote above clicks should have default value as 0. And you are making something like report page, you don’t want to add to_i for nil objects to the different expressions.
I wrote a small patch for this behavior:
module Extensions
module DefaultAttributeValue
def self.included(base)
base.send :extend, ClassMethods
end
module ClassMethods
def default_attribute_value(key, value)
self.class_eval %Q{
def #{key}
value = read_attribute(:#{key})
value || #{value}
end
}
end
end
end
end
# specs
require 'spec_helper'
class TestClass
include Extensions::DefaultAttributeValue
attr_accessor :key
default_attribute_value :key, 0
def read_attribute(key)
instance_variable_get("@#{key}")
end
end
describe Extensions::DefaultAttributeValue do
let(:object) { TestClass.new }
it { object.key.should == 0 }
context 'when key assigned' do
before { object.key = 1 }
it { object.key.should == 1 }
end
end
# example
class Stat #< ActiveRecord::Base
include Extensions::DefaultAttributeValue
default_attribute_value :clicks, 0
end