View

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. For a bundler-free environment, use Bundler.with_clean_env. 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 of the bundles:

```sh
~/my_projec…

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.

External content

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…

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…

How to horizontally center absolute positioned container with CSS

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.


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

// SASS
$container_width: 100px
.container
  width: $container_width
  margin: 0 auto

However, this w…

Center a float horizontally

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 can be useful if you want to center something and at the same time make its width automatically fit some content.

Use this SASS:

.center_float_outer_container
  overflo...

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…

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 …

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

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…

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
 ...

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…

External content

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.

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…

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…

External content

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.

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.

View
3345 cards