OpenStack instance not configuring network (DHCP) correctly

We ran into trouble when adding additional compute units to our railscomplete Hosting environment lately.

VM-instances on the new compute units where booting and requesting private IP addresses via DHCP correctly (DHCPDiscover), but after the answer of the dnsmasq dhcp server (DHCPOffer) we did not see any further traffic on the host machine. FYI: The instance should request the IP via DHCPRequest which in turn should be acknowledged by a DHCPAcknowledgment packet.

We assumed this DHCP UDP traffic did not...

Tell RVM which patch level you mean by "1.8.7" or "1.9.3"

When you download or upgrade RVM it has a hardcoded notion which patch level it considers to be "1.9.3".

This can give you errors like "ruby-1.9.3-p392 is not installed" even if you have another Ruby 1.9.3 that will do.

The solution is to define an alias:

rvm alias create 1.9.3 ruby-1.9.3-p385

Fuzzy matching

Another solution is to use rvm with the fuzzy flag, as stated by mpapis.

rvm use --fuzzy .

This will make rvm more intelligent in the Ruby selection. To always do fuzz...

Scaling Pinterest - From 0 to 10s of Billions of Page Views a Month in Two Years

Awesome battle report from Pinterest trying to scale their setup using different approaches.

When you push something to the limit all technologies fail in their own special way. This lead them to evaluate tool choices with a preference for tools that are: mature; really good and simple; well known and liked; well supported; consistently good performers; failure free as possible; free. Using these criteria they selected: MySQL, Solr, Memcache, and Redis. Cassandra and Mongo were dropped.

How to discard a surrounding Bundler environment

tl;dr: Ruby's Bundler environment is passed on to system calls, which may not be what you may want as it changes gem and binary lookup. Use Bundler.with_original_env to restore the environment's state before Bundler was launched. Do this whenever you want to execute shell commands inside other bundles.

Example outline

Consider this setup:

my_project/Gemfile     # says: gem 'rails', '~> 3.0.0'
my_project/foo/Gemfile # says: gem 'rails', '~> 3.2.0'

And, just to confirm this, these are the installed Rails versions for each ...

How to fix: "unexpected token" error for JSON.parse

When using the json gem, you might run into this error when using JSON.parse:

>> json = 'foo'.to_json
>> JSON.parse(json)
JSON::ParserError: 757: unexpected token at '"foo"'
	from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
	from /.../gems/json-1.7.7/lib/json/common.rb:155:in `parse'
	from (irb):1

Why?

The error above happens because the JSON you supplied is invalid.

While to_json does work correctly, the result itself is not JSON that can be parsed back, as that s...

kamens/jQuery-menu-aim

jQuery plugin to fire events when user's cursor aims at particular dropdown menu items. For making responsive mega dropdowns like Amazon's.

How to access your Rails session ID

This only works when you actually have a session ID (not the case for Rails' CookieStore, for example):

request.session_options[:id]
# => "142b17ab075e71f2a2e2543c6ae34b94"

Note that it's a bad idea to expose your session ID, so be careful what you use this for.

Controller specs do not persist the Rails session across requests of the same spec

In specs, the session never persists but is always a new object for each request. Data put into the session in a previous request is lost. Here is how to circumvent that.

What's going on?

You are making ActionController::TestRequests in your specs, and their #initialize method does this:

self.session = TestSession.new

This means that each time you say something like "get :index", the session in your controller will just be a new one, and you won't see ...

Firefox >= 23 will block mixed content when using SSL

Non-SSL contents on SSL pages are blocked by default

Bug 834836 – Turn on pref to block mixed active content

Firefox 18 introduced preferences to block loading contents from non-SSL (http) sites on SSL (https) pages. One of those preferences, security.mixed_content.block_active_content is now enabled by default in order to enhance user security. That means insecure scripts, stylesheets, plug-in contents, inline frames, Web fonts and WebSockets are blocked on secure pages, and a notification is displayed instead. It will not block...

parallel_tests: Disable parallel run for tagged scenarios

Note: This technique is confusing and slows down your test suite.


Copy the attached code to features/support. This gets you a new Cucumber tag @no_parallel which ensures that the tagged scenario does not run in parallel with other scenarios that are tagged with @no_parallel. Other scenarios not tagged will @no_parallel can still run in parallel with the tagged test. Please read the previous sentence again.

This can help when multiple test processes that access a single resource that is hard to shar...

Markdown-like emphasizing for text fields

Say you want to allow users to emphasize some string, but the whole markdown thing would be far too much. The helper method below does a basic replacement of **some text** with <strong>some text</strong>.

Usage: <%=md @question.title %>.

  def custom_markdown(prose)
    markdown = String.new.html_safe
    markdown << prose.to_str # make sure the prose gets escaped, even if it is an html_safe string
    markdown.gsub(/(\*\*)(.*?)(\*\*)/, '<strong>\2</strong>').html_safe
  end
  alias_method :md, :custom_markdown

How to rotate log files explicitly

Usually, the logrotate service takes care of renaming log files each night or so to avoid logs becoming huge. That will rename your.log to your.log.1, the next time to your.log.2.gz, etc. Here is how to make that happen out of band (you should rarely need to do that).

Logrotate won't touch all your logs automagically. There is a config file for each service which you can tell logrotate to use.

So if you need logs to be rotated right now, do this (as root):

logrotate --force PATH_TO_CONFIG_FILE

For example, to rotate all y...

What `var` actually does in Javascript

TL;DR: Variables not declared using var are stored outside the current scope, most likely in the global scope (which is window in web-browsers).


Declaring a variable in Javascript is done like var x = 5. This creates a new variable in the current scope (e.g. the function you're in). What happens when don't use var?

Javascript needs to be clever when you do an assignment without declaring a variable, e.g. x = 7. To find that variable,

  • it first looks up x in the current scope
  • next, it goes up the scope chain, lookin...

ApacheBench may return "Failed requests" for successful requests

When you use ab to do some performance benchmarking, you might run into output like this:

Complete requests:      200
Failed requests:        5
   (Connect: 0, Receive: 0, Length: 5, Exceptions: 0)

Note that in our example these "Failed requests" actually never failed.\
For some requests, the application just returned a response with a different content length than the first response. This is indicated by the "Length: 5" bit in the example above.

If you see requests that failed with other kinds of errors, they probably fail...

How to horizontally center absolute positioned container with CSS

Find out in this short guide, how to horizontally center a absolute positioned container with CSS.

Note: We have a card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.


Horizontally centering a static element in CSS is normally handled by setting the left and right margins to auto, for example:

// SA...

YAML syntax compared with Ruby syntax

yaml4r is a juxtaposition of yaml documents and their Ruby couterpart. Thus, it does a great job as YAML-doc, e.g. when writing Rails locale files. Did you know that ...

  • << is a merge key (similar to & in SASS)
  • there are variables, called aliases. Definition: &alias Some content, usage: *alias.

Caveats

Specifying a key twice does not merge the sub keys, but override the first definition, e.g.

de:
  car: # overridden
    door: Tür
 ...

Article "Pricing Experiments You Might Not Know, But Can Learn From"

We all struggle with pricing. Here is some interesting information that helps you with your pricing decisions.

Center a float horizontally

This card shows you how to center a float horizontally in CSS. Also: find out what techniques are available for your use case and browser requirements in the card linked below.

Note: We have card with all CSS centering options. You probably want to head over there and get an overview over what techniques are available for your use case and browser requirements.


If you cannot use display: inline-block, centering a float ...

Rails: How to use a n:m association as 1:n association

Sometimes you might want to limit the number of associated records in a has_many association, but cannot add a foreign key to the other model (using belongs_to).

There are many takes on limiting the number of associated records in has_many associations, but none feels smooth.

However, when your...

How to use helper methods in a controller

Rails 3+

view_context.helper_method('args')

Rails 2

ApplicationController.helpers.helper_method('args')

Also see How to use helper methods inside a model.

How to set the user agent in tests

The User-Agent HTTP header identifies the client and is sent by "regular" browsers, search engine crawlers, or other web client software.

Cucumber

In Rack::Test, you can set your user agent like this on Capybara:

Given /^my user agent is "(.+)"$/ do |agent|
  page.driver.browser.header('User-Agent', agent)
  # Or, for older Capybaras:
  # page.driver.header('User-Agent', agent)
end

For Selenium tests with Firefox, it seems you can set the general.useragent.override profile setting to your preferred value. [See StackOver...

Spreewald: When using `patiently do`, don't reuse existing variable names

Spreewald's patiently repeats the given block again and again until it either passes or times out.

Be careful to give patiently a block that can actually be repeated. E.g. the following block can not be repeated:

Given /^the field "(.*?)" is empty$/ do |field|
  patiently do
    field = find_field(field)
    field.text.should be_blank
  end
end

The reason the above code will fa...

def vs. define_method

Ever wondered about the difference between def and define_method? Turns out there are three implicit contexts in Ruby. def and define_method differ in which one they use.

def

  • Ruby keyword, starts a method definition
  • Opens a new, isolated scope. Variables defined outside are not accessible inside and vice versa.
  • Defines an instance method on the receiver (specified before the method name, e.g. def object.foo); implicit receiver is the default definee

The default definee is not self and...