How Ruby lets you keep script and data in *one* file
The __END__
keyword tells Ruby where a file ends – but you don't have to stop there. Any text you add after it is accessible via the DATA
object.
The attached example file data.rb
looks like this:
puts DATA.read
__END__
DATA is a File object to everything in the current file after "__END__"
Running it with ruby data.rb
prints:
DATA is a File object to everything in the current file after "__END__"
Creating a Grid for Product View for a eCommerce Site
Randy Hoyt is presenting a way to display something (e.g. products) in a grid. It's responsive, too!
Rspec_spinner or cucumber_spinner get into an infinite loop
Chances are, something in your project uses the mathn
library, which is known to cause infinite loops when rendering the progress bar. If so, this will probably fix it.
Workaround for broken integer division after requiring the mathn library
Ruby's mathn library changes Fixnum
division to work with exact Rational
s, so
2 / 3 => 0
2 / 3 * 3 => 0
require 'mathn'
2 / 3 => Rational(2,3)
2 / 3 * 3 => 2
While this might sometimes be quite neat, it's a nightmare if this gets required by some gem that suddenly redefines integer division across your whole project. Known culprits are the otherwise excellent distribution and [GetText](https://g...
An easy demonstration of what Twitter Bootstrap does
Holly Schinsky from Adobe shows some of Bootstrap's capabilities. The combination of explanation, screenshots and source code makes it easy to understand
A jQuery plugin pattern every jQuery plugin should use
Many jQuery plugins suffer from a good plugin architecture. When you write jQuery plugins you should use the plugin pattern described in this article which makes your plugin highly customizable and extensible.
Related article with patterns for namespaced jquery plugins (more detailed)
Get rid of WARNING: Nokogiri was built against LibXML version 2.7.7, but has dynamically loaded 2.7.8
If you get this warning on your local machine one of these steps might help:
Rebuilt the gem with the newer library
gem install --no-rdoc --no-ri nokogiri -- --with-xml2-include=/opt/local/include/libxml2 --with-xml2-lib=/opt/local/lib
If you still get the error, try to uninstall all nokogiri versions with
gem uninstall nokogiri
and install nokogiri again.
Fixing the issue on servers
However, on our servers this probably will not work. On the server, gems are stored in the ../shared/bundle/ruby/:version/gems
dire...
Howto transfer a single mysql table between several deployment stages
Example task: Multiply the table holidays
between several stages.
-
Open two terminals:
shell-for stage_1 shell-for stage_2
-
Get the stage1 and stage2 MySQL credentials:
cat /opt/www/the_stage.host.tld/current/config/database.yml cat config/database.yml # should do it
-
Dump the table to a path reachable by the stage2 user (e.g. home):
mysqldump -h mysql1 -u stage_1_user -p stage_1_database table_name > ~/table_name_dump.mysql # Select certain records using --where "some_id > 666"
(-...
Asset pipeline may break Javascript for IE (but only on production)
If some of your JavaScripts fail on Internet Explorer, but only in staging or production environments, chances are that JavaScript compression is the culprit.
By default, Rails 3.2 compresses JavaScript with UglifyJS. I have seen a few cases where this actually breaks functioning JavaScript on IE (one example is the CKEditor).
I fixed this by switching to Yahoo's YUI Compressor.
To do this, do the following:
- replace the
uglifier
gem with theyui-compressor
gem...
Cucumber step to interact with an iframe using Capybara webdriver
Give your iframe
a name attribute (i.e. <iframe name="myframe">
) and then simply use
When I press "Foo" in the iframe "myframe"
Then I should see "Bar!" in the iframe "myframe"
Step as follows:
Then /^(.*) in the iframe "([^\"]+)"$/ do |step, iframe_name|
browser = page.driver.browser
browser.switch_to.frame(iframe_name)
step(step)
browser.switch_to.default_content
end
Machinist blueprints do not work with a column :display
This didn't work for me. Seems display
is already taken in Machinist
.
# in spec/support/blueprints.rb
Partner.blueprint do
company_name
display { true }
end
Unsaved record disappears when assigning to an association
If this happens to you:
user.avatar = Avatar.new
user.avatar # => nil
(where avatar
is a belongs_to
), you probably declared your association incorrectly.
Always do
class User < ActiveRecord::Base
belongs_to :avatar
end
and never
class User < ActiveRecord::Base
belongs_to 'avatar'
end
exception_notification: Send exception mails in models
You're using exception_notification and want to send exception mails within a model. Here's how.
The ExceptionNotifier class has a method notify_exception
for that. Simply pass an exception:
ExceptionNotifier.notify_exception Exception.new("testfoo")
=> #<Mail::Message:77493640, Multipart: false, Headers: <Date: Mon, 24 Sep 2012 13:37:00 +0200>,
<From: foo@example.com>,
<To: ["fail@failtrain.com", "fail@failbus.org"]>,
<Message-ID: <5060543b3759_212311986a0305e...
Git: How to look at the stash
Browsing the git stash is a bit tricky. Here is how to see the changes without applying them:
git
command on the console
The following will give you the diff of the topmost stash item:
git stash show -u
But what about other items on the stash?
Well, you can list them like this:
$ git stash list
stash@{0}: WIP on feature/foo
stash@{1}: WIP on feature/bar
stash@{2}: WIP on fix/baz
All those stashed changes have their own reference (like branch names) that you can look at, like `stas...
Migrating to Spreewald
This describes how to migrate an existing cucumber test suite to Spreewald.
-
Add the gem
-
Include spreewald into your cucumber environment by putting
require 'spreewald/web_steps'
require 'spreewald/email_steps'
# ...
or just
require 'spreewald/all_steps'
into yoursupport/env.rb
. -
Look through your step definitions for everything that might be included in Spreewald. Candidates are
web_steps
,shared_steps
,table_steps
, `em...
How to not leave trailing whitespace (using your editor or Git)
There is no reason to leave trailing whitespace characters in your project's files, so don't add any.
A git diff --check
will tell you if there are any and you should not commit when you see them. So go ahead and switch your editor/IDE to automatically remove them for you.
Below are a few instructions on how to get them removed by your favorite IDE or editor.
Note that except for RubyMine, the following changes will remove trailing white-space on all lines, not only those that you changed.
While this should not be a problem if your proje...
Using before(:context) / before(:all) in RSpec will cause you lots of trouble unless you know what you are doing
TL;DR Avoid before(:context)
(formerly before(:all)
), use before(:example)
(formerly before(:each)
) instead.
If you do use before(:context)
, you need to know what you are doing and take care of any cleanup yourself.
Why?
Understand this:
-
before(:context)
is run when thecontext
/describe
block begins, -
before(:context)
is run outside of transactions, so data created here will bleed into other specs -
before(:example)
is run before each spec inside it,
Generally, you'll want a clean setup for each s...
Paperclip: undefined method `to_file' for #<Paperclip::Attachment:0000> (NoMethodError)
to_file
has been removed in Paperclip 3.0.1.
Instead of using File
to access Paperclip storage objects (like this: File.read(file.to_file.path)
) you can use
Paperclip.io_adapters.for(file).read
Git basics: checkout vs. reset
Today I got a better understanding of how git works, in particular what git checkout
and git reset
do.
Git basics
- A commit holds a certain state of a directory and a pointer to its antecedent commit.
- A commit is identified by a so-called ref looking something like
7153617ff70e716e229a823cdd205ebb13fa314d
. - HEAD is a pointer that is always pointing at the commit you are currently working on. Usually, it is pointing to a branch which is pointing to that commit.
- Branches are nothing but pointers to commits. Y...
CSS Animations Media Queries
CSS transitions make your responsive websites smoother and more professional. It's easy and already there. Use it!
ActionMailer sometimes breaks e-mails with multiple recipients in Rails 2
The ActionMailer in Rails 2 depends on a buggy version of TMail, which sometimes inserts a blank line into the mail header when sending a mail to multiple recipients. This makes the header end prematurely.
The reason why this is not exploding in your face all the time is that when you are relaying your e-mail through an MTA like Exim, it will fix this for you.
Fix for Rails if you don't have an awesome MTA
TMail is no longer maintained. The bug is fixed...
How to convert an OpenStruct to a Hash
Simply use OpenStruct#to_h
to receive an OpenStruct's hash representation.
In older Rubies you need OpenStruct#marshal_dump
instead.
Ruby 2.0+
>> OpenStruct.new(foo: 23, bar: 42).to_h
=> { :foo => 23, :bar => 42 }
Ruby 1.9.3 and 1.8.7
>> OpenStruct.new(:foo => 23, :bar => 42).marshal_dump
=> { :foo => 23, :bar => 42 }
Both approaches will return the underlying hash table (a clone of it in Ruby 2.0+).
Distribute files from a private bucket on AWS S3
Given you store files on Amazon S3 and you need to stream those files out to people while you don't want them to be able to distribute the content simply by sharing the S3 URL.
You could either mark the bucket as private and fetch the appropriate files from S3 to your application server and stream them to the client finally. While this is possible, I'd recommend to use what AWS calls "Query String Authentication".
If you're using Paperclip you can chose between two sto...
Create autocompletion dropdown for Cucumber paths in Textmate
Ever wanted autocompletion for paths from paths.rb
in Cucumber? This card lets you write your steps like this:
When I go to path *press tab now* # path is replaced with a list of all known Cucumber paths
This is how you do it
(key shortcuts apply for TextMate2)
-
Open the bundle editor (ctrl + alt + + B)
-
Create a new Item ( + N), select "Command"
-
Paste this:
^
#!/usr/bin/env ruby -wKU
require File.join(ENV['TM_SUPPORT_PATH'], 'lib', 'ui.rb')cucumber_paths = File.join ENV['TM_PROJECT_DIRECTORY'], 'features'...