If another session is accessing your database you are trying to reset or drop you might have seen the following error:
PG::ObjectInUse: ERROR: database "foo_development" is being accessed by other users
DETAIL: There is 1 other session using the database.
This could be the rails server, rubymine and many more. Beside terminating the session connection manually you can also find out the pid
and kill the process.
1. rails db
2. SELECT * FROM pg_stat_activity;
datid | 98359
datname | foo_developm...
return
to return from a method. return
accepts a value that will be the return value of the method call.break
to quit from a block and from the method that yielded to the block. break
accepts a value that supplies the result of the expression it is “breaking” out of.next
to skip the rest of the current iteration. next
accepts an argument that will be the result of that block iteration.The following method will serve as an example in the details below:
def example
puts yield
puts ...
I frequently find myself needing a combination of group_by
, count
and sort
for quick statistics. Here's a method on Enumerable
that combines the three:
module Enumerable
def count_by(&block)
list = group_by(&block)
.map { |key, items| [key, items.count] }
.sort_by(&:last)
Hash[list]
end
end
# Returns a Hash of { key => count } pairs (see below)
Just paste that snippet into a Rails console and use #count_by
now!
> User.all.co...
around(:suite)
does not exist.around(:all)
runs after before(:all)
and before after(:all)
.around(:each)
runs before before(:each)
and after after(:each)
.As this is not 100% obvious (and not yet documented) it is written down in this card. In RSpec 3 :each
has the alias :example
and :all
the alias :context
.
RSpec.configure do |config|
config.before(:suite) { puts 'BEFORE :suite' }
config.after(:suite) { puts 'AFTER :suite' }
end
describe 'order of hook execution' do
aroun...
There are many approaches out there how you can import data from a legacy application to a new application. Here is an approach which opens two database connections and uses active record for the legacy system, too:
1. Add you database information to you config/database.yml
.
data_migration:
database: your_application_data_migration
2. Create a separate application record for the data migration, e.g. in app/data_migration/migration_record.rb
. You will need to create an app/data_migration.rb
class first.
class DataMig...
You should prefer native promises to jQuery's Deferreds. Native promises are much faster than their jQuery equivalent.
Native promises are supported on all browsers except IE <=11, Android <= 4.4 and iOS <= 7.
If you need Promise
support for these old browsers y...
Native promises have no methods to inspect their state.
You can use the promiseState
function below to check whether a promise is fulfilled, rejected or still pending:
promiseState(promise, function(state) {
// `state` now either "pending", "fulfilled" or "rejected"
});
Note that the callback passed to promiseState
will be called asynchronously in the next [microtask](https://jakearchibald.com/2015/tasks-microtasks-queues-and-schedules/...
Use Traim to build a RESTful API for your ActiveRecord models with very little code.
Traim assumes your API resources will map 1:1 to your ActiveRecord models and database tables. This assumption usually falls apart after a few months into a project, so be ready to replace your Traim API with something more expressive afterwards.
Traim outputs a Rack application which you can either serve standalone or mount into your Rails app.
In the ruby shell (IRB) and rails console the return value of the previous command is saved in _
(underscore). This might come in handy if you forgot to save the value to a variable and further want to use it.
Example:
irb(main):001:0> 1 + 2
=> 3
irb(main):002:0> _
=> 3
irb(main):003:0> a = _
=> 3
ActiveRecord::RecordNotFound
errors provide quite meaningful error messages that can provide some insight on application details. Consider the following:
ActiveRecord::RecordNotFound: Couldn't find Organisation::Membership with 'id'=12 [WHERE "organisation_memberships"."user_id" = 1]
You should probably not simply render those error messages to the user directly. Instead you you might want to re-raise your own errors. ActiveRecord::RecordNotFound
provides you with methods :model
and :id
where you can get information about w...
This card will show you a cool way to define a class using Struct.new.
A common usecase for Structs are temporary data structures which just hold state and don't provide behaviour. In many cases you could use a simple hash as a data structure instead. However, a Struct provides you with a nice constructor, attribute accessors and complains if you try to access undefined attributes. Structs are easy to compare (by attributes). A struct gives meaning to the data.
Structs are great...
If you use the Better Errors gem, you will sometimes notice that it can be very slow. This is because it sometimes renders a huge amount of data that will actually be hard to render for your browser.
You can significantly improve performance by adding this to config/initializers/better_errors
:
if defined?(BetterErrors) && Rails.env.development?
module BetterErrorsHugeInspectWarning
def inspect_value(obj)
inspected = obj.inspect
if inspected.size > 20_000
inspec...
Shoulda Matchers don't provide canditional validations (validations with if:
option). Here is how to write tests for the condition:
class Employee < ActiveRecored::Base
validates :office, presence: true, if: manager?
def manager?
...
end
end
describe Employee do
describe '#office' do
context 'is a manager' do
before { allow(subject).to receive(:manager?).and_return(true) }
it { is_expected.to validate_presence_o...
When using GROUP BY
, MySQL now complains if the SELECT
includes columns which are not part of the GROUP BY
.
There could be multiple values for those columns per group but only one value can be picked for the results.
The default behaviour of MySQL prior to version 5.7 will not complain and arbitrarily choose a value. But this leads to non-deterministic results. So MySQL now has enabled the only_full_group_by
setting by default to prevent this.
In Rails this could lead to some trouble, because scopes do not have sp...
Nowadays it is fairly easy to intercept and modify mails globally before they are sent. All you have to do is register an interceptor class which responds to .delivering_email(message)
. This card will show you two common use cases.
Usually you want to prefix the subject line of emails with the current environment (except production) so you can differentiate between production mails and mails from other environments. Of course a...
Rails supports time zones, but there are several pitfalls. Most importantly because Time.now
and Time.current
are completely different things and code from gems might use one or the other.
Especially configuring an application that cares only about one time zone is a bit tricky.
The following was tested on Rails 5.1 but should apply to Rails 4.2 as well.
Your life will be easier if your application does not need to support time zones. Disable them like this:
config.time_zone = 'Berlin' # Your local ...
Webmocks hash_including
is similar to RSpec::Mocks::ArgumentMatchers#hash_including
. Be aware that hash_including
(webmock v3.0.1) doesn't parse integer values to String.
Without hash including you would say:
uri = URI('http://example.com/?foo=1&bar=2')
stub_request(:get, 'example.com').with(query: {foo: 1, bar: 2})
Net::HTTP.get(uri) # ===> Success
If you only want to check if foo
is present you can use hash_including
:
uri = URI('http://example.com/?foo=1&bar=2')
stub_request(:get, 'example.com').with(query: hash_i...
TLDR: Browser implementations of HTTP/2 push are horrible. You might end up with worse performance than without pushing. However, the article includes a great explanation of how HTTP/2 push are supposed to integrate with browser APIs.
Database connections are not thread-safe. That's why ActiveRecord uses a separate database connection for each thread.
For instance, the following code uses 3 database connections:
3.times do
Thread.new do
User.first # first database access makes a new connection
end
end
These three connections will remain connected to the database server after the threads terminate. This only affects threads that use ActiveRecord.
You can rely on Rails' various clean-up mechanisms to release connections, as outlined below. This may...
This card compares patterns to store trees in a relation database like MySQL or PostgreSQL. Implementation examples are for the ActiveRecord ORM used with Ruby on Rails, but the techniques can be implemented in any language or framework.
We will be using this example tree (from the acts_as_nested_set docs):
root
|
+-- Child 1
| |
| +-- Child 1.1
| |
| +-- Child 1.2
|
+-- ...
The parallel-gem is quite easy to use and can speed up rendering time if you want to render the same partial multiple times (e.g. for rendering long lists of things).
If your parallelized code talks to the database, you should ensure not to leak database connections.
Consider you want to render a list of groups with their members as json. You can use a partial for the rendering of group members, b...
When filling out forms in Selenium tests, Chrome shows the (usual) bubble, asking to store those credentials.
While the bubble does not interfere with tests, it is annoying when debugging tests. Here are two ways to disable it:
You can set profile preferences to disable the password manager like so:
prefs = {
'credentials_enable_service' => false,
'profile.password_manager_enabled' => false
}
Capybara::Selenium::Driver.new(app, browser: :chrome, prefs: prefs)
Sadly, there are no command line s...
Looks like ActiveState is trying to market a new Ruby distribution for Enterprises:
ActiveRuby Enterprise Edition is designed for businesses with large Ruby deployments in essential, mission-critical applications that, when down, could cost your business in lost revenue and a damaged reputation. Deploy Ruby with confidence knowing you're using the most secure, enterprise-grade builds for the platforms that power your business. You'll get priority access to our Ruby experts for technical support and best prac...
Using VCR to record communication with remote APIs is a great way to stub requests in tests. However, you may still want to look at the request data like the payload your application sent.
Using WebMock, this is simple: Make your request (which will record/play a VCR cassette), then ask WebMock about it:
expect(WebMock).to have_requested(:post, 'http://example.com').with(body: 'yolo')
Easy peasy.