Managing vendor assets in Rails with Bower
bower-rails is a great solution for managing vendored assets in your Rails app. It feels especially much more convenient and easier to update assets when going this way.
bower-rails generates a Bowerfile that works much like the Gemfile you're used to. Just specify your dependencies and run rake bower:install. You can find available packages here.
An example Bowerfile:
# ./Bowerfile
asset 'angular'
asset 'angular-i18n'
asset 'angular-ui-router'
asset 'angu...
Dealing with "TypeError: Converting circular structure to JSON" on JavaScript
JavaScript structures that include circular references can't be serialized with a"plain" JSON.stringify. Example:
a = { name: 'Groucho' };
b = { name: 'Harpo', sibling: a };
a.sibling = b;
Doing a JSON.stringify(a) will throw an error:
TypeError: Converting circular structure to JSON
There is not much you can do about that except specifying a custom serializer function that detects and cleans up circular references. There are existing solutions so you do not need to think of one yourself, like <https://githu...
Returning an empty ActiveRecord scope
Returning an empty scope can come in handy, e.g. as a default object. In Rails 4 you can achieve this by calling none on your ActiveRecord model.
MyModel.none # returns an empty ActiveRecord::Relation object
For older Rails versions you can use the attached initializer to get a none scope.
When Sass-generated stylesheets print a Encoding::CompatibilityError
We upgraded a Rails 2 application to Rails 3.2 and Ruby 2.1, changed the mysql adapter from mysql to mysql2, but did not activitate the asset pipeline. Instead we used Sass the old-school way (stylesheets in public/sass/*.sass) and relied on stylesheet_link_tag to activate the Sass compiler.
Now all Sass-generated stylesheets inserted the following text into body:before:
Encoding::CompatibilityError: incompatible character encodings: UTF-8 and ASCII-8BIT
I could get rid of this by removing all generated .css files in `...
Reveal the indexes of an ActiveRecord table
p ActiveRecord::Base.connection.indexes(:table_name)
CoffeeScript: How to instantiate a class with an attributes hash
This may be hard to find in the docs, but if you want CoffeeScript classes that instantiate their properties from a hash of attributes (like ActiveRecord), do it like this:
class User
constructor: ({ @name, @email }) ->
# empty contstructor is fine, CoffeeScript will do the magic.
Example:
var batman = new User(name: 'Bruce Wayne', email: 'batman@example.com')
batman.name # => 'Bruce Wayne'
Sending raw JSON data to a member action in a controller spec
This is what worked for me in a Rails 4:
# JSON data as first argument, then parameters
patch :update, { some: 'data' }.to_json, id: id, format: :json
HTML5: Allow to choose multiple files with a vanilla file picker
Modern browsers natively suppport file pickers that allow the user to choose multiple files at once. To activate this feature, set the multiple attribute:
<input type="file" name="images[]" multiple />
Or in a Rails view:
<%= file_field_tag "images[]", multiple: true %>
This works in IE10+.
Make sure that the field name ends in [] so your server-side code will parse the incoming files into an array. Obviously this naming convention is not compatible with default Rails nested attribute setters, so you'll need to write a form ...
Angular Filters
A collection of useful filters for AngularJS, e.g. for fuzzy string searching, displaying numbers as percentages an more.
Tagging in Rails 4 using Postgres Arrays
Usage:
class Document < ActiveRecord::Base
scope :any_tags, -> (tags){ where('tags && ARRAY[?]', tags) }
scope :all_tags, -> (tags){ where('tags @> ARRAY[?]', tags) }
end
Document.create(title: "PostgreSQL", tags: ["pg","rails"])
Document.any_tags('pg')
Document.all_tags(['pg', 'rails'])
Migration:
class CreateDocuments < ActiveRecord::Migration
def change
create_table :documents do |t|
t.string :title
t.string :tags, array: true, default: []
t.timestamps
end
add_index :documents, :ta...
Iterate over any enumerable with an index
tl;dr: Use with_index
ActiveRecord's find_each with index
If you do not provide a block to find_each, it will return an Enumerator for chaining with other methods:
Person.find_each.with_index do |person, index|
person.award_trophy(index + 1)
end
Ruby's map with index
Similarly, you may need an index when using other methods, like map, flat_map, detect (when you need the index for detection), or similar. Here is an example for map:
people...
rails/activeform
A different take on what we're doing with ActiveType. Since it lives under the rails organization it might be part of Rails 5?
Wrapping Your API In A Custom Ruby Gem
Nice tutorial about packaging Ruby bindings to your API in a Ruby gem, with tests using VCR casettes.
How to fix: Font too small when reading e-mails in Thunderbird
In Thunderbird, you can set custom font faces and sizes for reading plain-text e-mails. However, Thunderbird sometimes "randomly" does not respect your choices.
This is actually not a bug, but a rather weird feature: Fonts are defined per encoding of e-mails.
Some e-mails will be considered Unicode, some Western (ISO 8859-1), and some maybe yet another encoding.
The advanced font settings dialog by default just opens on "Western". Choose a different encoding from the "Fonts for" dropdown menu and you'll see that your custom font sett...
Backup an entire website using wget
You need to copy an entire website? Use wget like this:
wget -kr http://host.tld/
This will fetch all content (-r for recursive) and rewrite links inside the documents to make them suitable for local viewing (-k).
pdfkit/wkhtmltopdf: When a header is invisible
If you're using the :header_html option in PDFKit (or the corresponding --header-html option in wkhtmltopdf), and the header remains invisible, you need to add this to your header HTML:
<!doctype html>
The same applies to footers via footer_html
I'm sorry.
Eager-loading polymorphic associations
To avoid n+1 queries, you want to eager-load associated records if you know you need to access them later on.
The Rails docs say:
Eager loading is supported with polymorphic associations.
This is true, but has some caveats.
Example
Consider the following models:
class Image < ActiveRecord::Base; end
class Video < ActiveRecord::Base; end
class PageVersion < ActiveRecord::Base
belongs_to :primary_medium, polymorphic: true # may be Image or Video
end
class Page < ActiveRecord::Base
belongs_to ...
Rails 4.1+: New locale files require a Spring restart
So you want to organize your I18n using multiple .yml files but your Rails 4.1 application simply won't use any extra files in development? Spring is to blame.
Halt spring by running:
spring stop
The next time you spawn a bin/rails console or similar, your new translations will work.
You will need to repeat the above every time you create a new .yml file or rename existing ones.
:(
Pete Hunt: React - Rethinking Best Practices
Great introduction to React.js and the ideas behind it.
Use a Bash function to alias the rake command to Spring binstubs or "bundle exec" fallback
There are different ways to run rake:
- On Rails 4.1+ projects, you have Spring and its binstubs which dramatically improve boot-up time for Rake and similar. You need to run
bin/raketo use them. - On older projects, you want to run "bundle exec rake" to avoid those ugly "already activated rake x.y.z" errors that hit you when different rake versions are installed for your current Ruby.
Here is a solution that gives you a plain rake command which uses a binstubbed bin/rake if available and falls back to bundle exec rake if necessar...
Linux: Running a program with a different locale than your default
When your system is not running on English, you may sometimes want to run some applications and not use your system locale.
Use cases are scripts that parse output, or just using the (possibly) more common English labels or error messages. Here is how to do that.
I will use the date command and print the current weekday, just for the sake of an example.
Changing the locale using environment variables
Most often, setting LC_ALL for your command should be enough. The following was run on a system using a German locale.
$ date +%...
How Exchange handles multipart/alternative emails
In Rails, you can very easily send emails with HTML and plaintext bodies.
However, if you're trying to debug those using your normal email account, you might be out of luck: For some reason, Exchange servers will simply throw away the plaintext part of your mail, and just save the html part.
Change the existing order of an ActiveRecord scope
Use reorder to replace an existing order clause with a new expression.
The Curious Case of the Flip-Flop
The flip-flop operator is a hotly contested feature of Ruby. It's still struggling to find an idiomatic use case, except for a few very rarely needed things. It's not something you'll likely reach for on a daily, weekly or even monthly basis. The only thing you really need to know about it is what it does, and that's only in case you encounter it in someone else's code. Many even go as far to say not to use the flip-flop operator, that it only adds confusion.
My brain just melted.