Coffeescript: Caveat when cloning objects with fat-arrow methods
Coffeescript allows you to create classes whose methods are automatically bound to the correct this
. You can do this by using a fat arrow:
class Person
constructor: (name) ->
@name = name
sayHello: =>
alert("Hello, I am #{@name}")
An important caveat is that when you clone such an object, all of its methods are still bound to the original instance:
eve = new Person("Eve")
eve.sayHello() # => "Hello, I am Eve"
bob = _.clone(eve)
bob.name = "Bob"
bob.sayHello() # => "Hello, I am Eve"
I don't thin...
Clean up application servers when deploying
Our development process makes us deploy very often. As the number of releases grows, junk clogs up the hard drive of our application servers:
- Old release code
- Old
tmp
folders with compiled view templates etc. - Precompiled assets (Javascripts, images...) that no longer exist. When using the asset pipeline, Capistrano will symlink the
public/assets
directory toshared/assets
. This is cool since we can still serve previous assets after a new release, in the window where browser caches might still have references to old assets. But i...
JavaScript: How to generate a regular expression from a string
Getting a regular expression from a string in JavaScript is quite simple:
new RegExp('Hello Universe');
# => /Hello Universe/
You can also use special characters:
new RegExp('^(\\d+) users')
# => /^(\d+) users/
Our expression above now works only at the beginning of the matched string, looks for a number (\d+
[1]) and also captures that. Sweet.
However, mind that your input will not be magically escaped because of that:
new RegExp('makandra.com')
# => /makandra.com/
The above expression would match "`...
AngularJS: Access the scope for a rendered DOM element
This trick might be useful to implement more complicated directives in AngularJS. I needed it to do drag'n'drop in a hierarchical tree.
Let's say you have this $scope
in your Angular controller:
$scope.tasks = [
{ 'text': 'Task 1' },
{ 'text': 'Task 2' }
]
And you have this template:
<ul ng-repeat="task in tasks">
<li>
{{task.text}}
</li>
</ul>
Which renders this HTML:
<ul>
<li>Task 1</li>
<li>Task 2</li>
</ul>
If you'd like to access the scope bound to the second <li>
you can say this in jQ...
How to not die with ActionView::MissingTemplate when clients request weird formats
When HTTP clients make an request they can define which response formats they can process. They do it by adding a header to the HTTP request like this:
Accept: application/json
This means the client will only understand JSON responses.
When a Rails action is done, it will try to render a template for a format that the client understand. This means when all you are HTML templates, a request that only accepts application/json
will raise an error:
An ActionView::MissingTemplate occurred in pages#foo:
Missing templa...
Fixing authentication in legacy applications
Authentication is hard: there are many edge cases, and most users (including yourself) usually only go the "happy path" once and never see the edge cases. If you have rolled your own authentication, or been using older authentication solutions, or resorted to HTTP Basic Authentication, this card will tell you what to do to make your application safe.
Any application that stores sensitive data in the browser
That is: cookies, e.g. by offering a login.
- Ask the admins to [turn on SSL](https://makandracards.com/makandra/1416-integrate-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.
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...
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...
Test redirects to an external URL with Cucumber/Capybara
When a controller action redirects to an external URL (like http://somehost.com/some/path
) you will find that this is hard to test with Cucumber and Capybara:
- A non-Javascript Rack::Test scenario will just ignore the host and try to open
/some/path
in your local application - A Selenium test will actually follow the redirect, which you probably don't want either
There are two workarounds for this. You can use either, or a combination of both.
- Write a controller spec
Controller specs can test if a resp...
The Plight of Pinocchio: JavaScript's quest to become a real language - opensoul.org
Great presentation about writing Javascript like you write everything else: Well-structured and tested.
JavaScript is no longer a toy language. Many of our applications can’t function without it. If we are going to use JavaScript to do real things, we need to treat it like a real language, adopting the same practices we use with real languages.
This framework agnostic talk takes a serious look at how we develop JavaScript applications. Despite its prototypical nature, good object-oriented programming principles are still relevant. The...
What's in a View? A look at the alternatives
Great look at the tradeoffs between progressive enhancement with jQuery or similiar, vs. client-side views.
Chart.js - a promising JavaScript charting library with MIT-license
Chart.js seems to be a good alternative to Google's Chart API and other commercial chart drawing libraries.
- good looking charts
- canvas based (means less memory consumptive, but no interactivity out of the box)
- highly configurable
- good API and documentation
- just 4.5 kilobytes
- MIT license
- Browser support: all browsers supporting the canvas element (for IE8 and below, use the polyfill as describes in the [chart.js documentation...
JavaScript: Comparing objects or arrays for equality (not reference)
JavaScript has no built-in functions to compare two objects or arrays for equality of their contained values.
If your project uses Lodash or Underscore.js, you can use _.isEqual()
:
_.isEqual([1, 2], [2, 3]) // => false
_.isEqual([1, 2], [1, 2]) // => true
If your project already uses Unpoly you may also use up.util.isEqual()
in the same way:
up.util.isEqual([1, 2], [2, 3]) // => false
up.util.isEqual([1, 2], [1, 2]) // => true
If you are wri...
Selenium: How to close another tab (popup)
If you open a pop-up window [1] in your Selenium tests and you want to close it, you can do this:
# Find our target window
handle = page.driver.find_window("My window title")
# Close it
page.driver.browser.switch_to.window(handle)
page.driver.browser.close
# Have the Selenium driver point to another window
last_handle = page.driver.browser.window_handles.last
page.driver.browser.switch_to.window(last_handle)
Mind these:
-
find_window
returns a window handle, which is something like `"{485fa8bd-fa99-...
Fix error "invalid byte sequence in US-ASCII" in .js.erb files
This error can happen in Ruby 1.9.
To fix it, add the following line to the top of your .js.erb
file:
<%# @encoding: UTF-8 %>
Minified JavaScript and CSS
JavaScripts and CSS should be minified for production use.
In Rails 3.1+ the asset pipeline will take care of this. Thus you're best off using an uncompressed version of your Javascript in development. Also load the non-minified versions of libraries. This way debugging will be easier and you will still get all the minification love once deployed.
In Rails 2.3 and 3.0 you should at least embed external JavaScript libraries in minified form, using something like JavaScript compressor.
Capturing signatures on a touch device
If you need to capture signatures on an IPad or similar device, you can use Thomas J Bradley's excellent Signature Pad plugin for jQuery.
To implement, just follow the steps on the Github page.
The form
If you have a model Signature
with name: string, signature: text
, you can use it with regular rails form like this:
- form_for @signature, :html => { :class => 'signature_form' } do |form|
%dl
%dt
= form...
Prevent double clicks on link_to_remote (simple case)
This works well in the simplified case, when your link disappears after it was clicked.
Let link_to_remote behave as „disabled“ after the first click. Use the :before
hook to replace the orignal link with a link that does nothing but looks like the original link:
:ruby
label = "do_something"
dummy_link = link_to(label)
other_attributes_hash = { :url => ..., :method => ..., ... }
disable_link_option = { :before => "$('your_link_selector').html('#{escape_javascript(dummy_link)}'" } # jquery
= link_to_remote(label, other_att...
hint.css - A tooltip library in CSS
A tooltip library that does not use Javascript. Works in IE9+.
This library (or the technique used by it) could be a great choice for projects with a lot of tooltips, which are hard to do fast with Javascript.
Test that a form field is visible with Cucumber/Capybara
Spreewald now comes with a step that tests if a form field is visible:
Then the "Due date" field should be visible
But the "Author" field should not be visible
The step works by looking up the field for the given label, then checks if that field is hidden via CSS (or Javascript).
It is not currently tested if the label is visible or hidden. For this see: [Check that an element is visible or hidden via CSS with Cucumber/Capybara](https://makandracards.com/makandra/1049-check-that-an-elem...
Behave.js
Behave.js is a lightweight library for adding IDE style behaviors to plain text areas, making it much more enjoyable to write code in. Features include:
- Custom Code/Behavior Fencing
- Hard and Soft Tabs
- Auto Open/Close Parenthesis, Brackets, Braces, Double and Single Quotes
- Auto delete a paired character
- Overwrite a paired character
- Multi-line Indentation/Unindentation
- Automatic Indentation
Prism.js: simple, fast and lightweight syntax highlighting
Prism is a new lightweight, extensible syntax highlighter, built with modern web standards in mind. It’s a spin-off from Dabblet and is tested there daily by thousands.
Geocoding Strategies - Google Maps API
The attached article outlines considerations when choosing client-side vs. server-side implementations of the Google Geocoding APIs (geocoder, directions, not maps drawing). The main points are:
- On the server side you only get a fixed daily request quota
- On the client side the quota is per-client, so basically unlimited
- When implementing APIs on the server-side, be aware that quota is measured by IP. When hosting in the cloud **you don't always know which other services might...