Newly installed Android SDKs don't appear as build targets in Eclipse
You need to restart Eclipse.
Javascript equivalent of Ruby's array.collect(&:method)
The most common use case for Ruby's #collect
is to call a method on each list element and collect the return values in a new array:
['hello', 'world', 'this', 'is', 'nice'].collect(&:length)
# => [5, 5, 4, 2, 4]
Although there is no equivalent to this idiom in naked Javascript, there is a way to collect object properties (but not method results) if you are using common Javascript libraries.
If you are using jQuery with the Underscore.js utility library, you can use [pluck
](htt...
Rails logs are not flushed automatically (in Rake tasks)
The Rails logger will store its content in a buffer and write it into the file system every 1000 lines. This will come back to bite you when using Rails.logger.info
to write log output during Rake tasks or on a production console.
You often won't notice this because for the development
and test
environments auto_flushing
is set to write after each line. On production environments the Rails logger writes only every 1000 lines -- and not upon shell or script ter...
Monitor a Rake task with God
In order to monitor a Rake task using God your Rake file must write a file with its process ID (PID) to a path determined by God. This way God can check whether the Rake process is still alive.
Here is how to do this: In your God config, call the Rake task with an environment variable PIDFILE
. This variable should equal the PID file path desired by God:
God.watch do |w|
w.dir = "#{rails_root}"
w.name = "my_task"
w.interval = 10.seconds
w.pid_file = "#{rails_root}/tmp/pids/#{w.name}...
You can use any RSpec matcher to match arguments of method calls
RSpec lets you define the arguments with which you expect a method to be invoked:
subject.should_receive(:say).with('hello')
Sometimes you don't care about the exact arguments. For such cases RSpec comes with argument constraints like anything
or hash_including
:
subject.should_receive(:update_attributes).with(hash_including(:message => 'hi world'))
You can go even further and use any R...
Don't call gsub on safe strings
Calling #gsub
on a string that was previously marked as #html_safe
will lead to unexpected behavior. E. g. backreferences to captured groups ($1
, $2
) will be nil
even if the group was matched.
There is no universal workaround available since you can't expect #html_safe
strings to still be safe after using gsub
on them.
You can, however, fix the $1
gsub
behavior on html_safe strings.
Capybara can match elements outside of <body>
Capybara will match elements outside of a page's <body>
tag.
For example, the step definitions below match <link>
nodes in a page's <head>
:
Then /^my browser should auto-discover the "([^"]*)" feed$/ do |slug|
page.should have_css(
'head link' +
'[rel="alternate"]' +
"[href='http://www.example.com/#{slug}/feed.rss']" +
'[title="RSS feed (all cards)"]' +
'[type="application/rss+xml"]',
visible: false
)
end
Then /^my browser should not auto-discover any RSS fe...
Mute a skype chat
If you want to stop getting notified about new messages in a Skype chat (but not leave it altogether), you can type
/alertsoff
into the chat. This will only affect this one chat.
To only be notified when certain keywords appear in the conversation, use
/alertson KEYWORD
Note that multiple keywords must be defined with one call, as each call will overwrite previous keywords. Separate them by spaces:
/alertson KEYWORD1 KEYWORD2
Keywords are case-insensitive.
To revert to standard behaviour, use simply
/alertson
...
Mailcatcher: An alternative to inaction_mailer
Looks simpler than inaction_mailer:
gem install mailcatcher
mailcatcher
Setup Rails to send mails to 127.0.0.1:1025. Usually you want the following config in config/environments/development.rb
and maybe in test.rb
or cucumber.rb
.
config.action_mailer.delivery_method = :smtp
config.action_mailer.smtp_settings = {
:address => 'localhost',
:port => 1025
}
Now you can see sent mails in your browser when opening http://127.0.0.1:1080
Note: In order to s...
How to update a MySQL column with ascending numbers
Given the problem you have a new column postion and that column should be updated for all existing rows with ascending numbers. Furthermore these numbers should be generated by a special order. In order to achieve that you could do the following:
execute "SET @pos := 0;"
update " UPDATE pages SET position = ( SELECT @pos := @pos + 1 ) ORDER BY updated_at DESC;"
How to change the order of nested forms being rendered (especially blank forms)
Generally for nested forms, a blank form is placed below all other existing object forms. If you would like to change the position of the blank form(s) you can reorder the object's one-to-many association. For example you can put the blank form on top with the following snippet:
actors = movie.actors
actors.build
actors.unshift(actors.pop(1)) # won't work with Rails 4+
Because build_for_form
creates new objects and ap...
Defining to_json and avoiding errors
Defining a custom to_json
method for your classes can be useful. Do it properly or you will "randomly" get errors like these:
wrong number of arguments (1 for 0) (ArgumentError)
wrong number of arguments (0 for 1) (ArgumentError)
Take a look at how Object#to_json
is defined:
def to_json(options = nil)
ActiveSupport::JSON.encode(as_json(options))
end
Make sure you at least take the options
argument -- or, if you don't need to look at it, just grab and (if you need to) pass on any arguments you receive like this...
How to grep recursively on Solaris
grep -r
doesn't work on Solaris. You can only grep on files in the current directory.
A workaround is to use grep
with find
:
find ./ -type f -exec grep "foo" {} +
Start Rails console or server with debugger
When you require the Ruby debugger to be available from your Rails console (e.g. you want to inspect a method's magic), you need to enable it explicitly:
script/console --debugger
If you cannot access local variables etc, see this card.
WEBrick
For WEBrick, enable it similarly:
script/server --debugger
Git: Change author of a commit
Using git rebase
can be painful but luckily you can resort to cheating with git reset
and committing anew.
Now what if you wanted to rebase commits of other people and still wish them to be the authors of their code? Easy: make them the author of a commit you made.
When you have freshly staged changes that are ready to be committed, just use the --author
switch:
git commit -m "Hello Universe" --author="Philip J Fry <someone@example.com>"
If...
Properly adding fields with default values to a model
When adding a new field to your model's database table, don't set any defaults in the database.
It makes people wonder why they get such values when reading attributes.\
Why? Because nobody looks at the database layout since such things are part of your application's logic -- and thus they belong into the corresponding model.
How to
Do it like this:
-
In your migration, after adding the field, update all fields to your desired default:
update "UPDATE users SET locked = #{quoted_false};"
-
In your model, set a defau...
Single step and slow motion for cucumber scenarios using @javascript selenium
Single step and slow motion for Cucumber scenarios can come in handy, especially in @javascript
scenarios.
# features/support/examiners.rb
AfterStep('@slow_motion') do
sleep 2
end
AfterStep('@single_step') do
print "Single Stepping. Hit enter to continue"
STDIN.getc
end
If you're using spreewald, these tags are available as @slow-motion
and @single-step
(with dashes instead of underscores).
Note: You can also [prevent the selenium webbrowser wind...
Open a MySQL shell using credentials from database.yml
In order to open a MySQL shell without the need to enter user and password, you can say the following in any Rails 2 project:
script/dbconsole -p
In Rails 3 you can say:
rails dbconsole -p
If you'd like to enter a database for an environment other than development
you can say:
script/dbconsole -p staging
Install the Oniguruma gem
Oniguruma is an advanced regular expression engine for Ruby.
Install Oniguruma with binary dependencies like this:
sudo apt-get install libonig2 libonig-dev
sudo gem install oniguruma
On the Mac do:
brew install oniguruma
sudo gem install oniguruma
How to use CSS3 gradients in Opera
Since version 11.10 Opera provides support for linear gradients using -o-linear-gradient
.
The syntax is pretty similar to Mozilla's -moz-linear-gradient
. This will create a vertical gradient from yellow to red:
background-image: -o-linear-gradient(top, #ff0, #f00);
The first parameter defines where the gradient starts and which direction it will go. \
You can use top
/left
/bottom
/right
(and combinations of those) but also set any angle you like (0° being the left side, going counter-clock-wise):
background-image: -o-l...
Use SSL for Amazon RDS / MySQL (and your Rails app)
In case you have sensitive data within your RDS instance, you want to use encrypted connections between your application and RDS instances. If you're using MySQL on RDS, here's what to do:
-
Download the AWS CA file and copy it to the machine you want to connect from: http://s3.amazonaws.com/rds-downloads/mysql-ssl-ca-cert.pem
As far as I could find out, you (currently) cannot access further details of the SSL configuration (such as public key). -
Try to connect using MySQL client
`% mysql -uyour_username -p -h rds_hostname_from_...
Making the rails 3.1. asset pipeline and asset precompiling work in production mode
Recently, we had an interesting lunch-break with the rails 3.1. asset-pipeline in production mode. Daniel Zahn made a blogpost about our journey, precompiling assets, fingerprinting, Haml, Sass & Compass and what he calls "the dark heinous hutch".
Removing ANSI color codes from Rails logs
The colors in Rails log files are helpful when watching them but, since they are ANSI color codes like ^[[4;36;1m
, can be annoying when you are reading the logs with a tool that does just prints those control characters (like less
or vim
).
Remove them with sed
:
cat staging.log | sed -r "s/\x1B\[([0-9]{1,3}((;[0-9]{1,3})*)?)?[m|K]//g"
This will print the log without colors to your terminal. You can pipe the result into less
for example.
To have a file you can vim
around with, just write that output into a new file:
ca...
Usage of RSpec's raise_error
Never use raise_error
without specifying the Error you expect.
expect { do_a_lot_of_complicated_stuff }.to raise_error
will be green if you make any error in programming. E.g. a simple typo would make the test above green. The block will catch the Spec::
exception and the test will be happy.
Be sure to always have custom errors in your models and raise them in a manner that lets you know what went wrong.
expect { execute_payment! }.to raise_error(PayPal...