Rails 2.3.x sometimes renders localized views with the wrong content type
Under certain (unknown) circumstances, Rails will give localized files an invalid content-type in the Response header. For me, after requesting corporate_information
and rendering corporate_information.de.html.haml
, Rails sent a content-type of de.html
instead of the expected text/html
.
There are some discussions on this topic that offer workarounds, but no...
Cucumber: Wait for any requests to finish before moving on to the next scenario
Background
Generally, Selenium tests use the browser to interact with the page. If it's unavailable, a timeout error is thrown.
Now, consider a scenario like this:
@javascript
Scenario: Receive an e-mail after clicking the fancy link
When I follow "fancy link"
Then I should have an e-mail with the subject "Hello"
When the last step in the scenario passes, you are done. Right? Wrong.
Why it's not enough
What if clicking our "fancy link" above sends the e-mail that we expect, but it also does stuff on the server...
CSS3 Animated Loading Bar
Shows how to implement an animated progress bar in pure CSS, without animated GIFs, Javascript or Flash.
IcoMoon icons
Huge set of 315 free vector icons. You can choose which one you'd like, add your own SVGs, then download everything as an icon font or series of PNGs.
You can get up to 925 icons once you pay $59.
Regex pattern to validate email addresses
Our most recent pattern is
EMAIL = /\A[a-z0-9\+\-_\.]+@[a-z\d\-.]+\.[a-z]+\z/i
Notes
- Don't replace
[a-z0-9\+\-_\.]
with\w
! Otherwise the pattern would allowß
s and many other invalid characters. - The email address standard allows more patterns of emails than those which work in practice (e.g.
a@a
is valid). In result our pattern is more strictly. - Caution:
john..doe@example.com
andjohn.doe@example..com
are accepted as well.
Ruby: Extract the hostname from a URL
url = 'http://www.foocorp.com/foo/bar'
URI.parse(url).host
# => www.foocorp.com
Note that this will raise an error if the given argument is not a URL.
If you need the host's full URL without path, query, fragment etc., use URI.join
with a clever twist:
url = 'http://www.foocorp.com:33546/foo/bar?query=foobar#hash'
URI.join url, '/'
# => http://www.foocorp.com:33546/
Git: Show current branch name only
While git branch
will show you all branches and highlight the current one with an asterisk, it can be too cumbersome when working with lots of branches.
To show only the branch you are currently on, use:
git rev-parse --abbrev-ref HEAD
Haml: Fix problem with HTML-escaped single quotes in text fields
Haml 3.1.2 displays single quotes in FormBuilder#text_ field
html escaped. You may see something like that:
David's Chapter
Looking at the page's HTML, your field's values will be doubly escaped:
<input ... value="David&#x27;s Chapter" />
Updating Haml to 3.1.5 or newer will fix it.
Advice: Reduce scopes with joins to simple IN-queries
In theory you can take any scope and extend it with additional joins or conditions. We call this chaining scopes.
In practice chaining becomes problematic when scope chains grow more complex. In particular having JOINs
in your scope will reduce the scope's ability to be chained with additional JOINs
without crashes or side effects. This is because ActiveRecord doesn't really "understand" your scope chain, it only mashes together strings that mostly happen to look like a MySQL query in the end.
**I don't generally advice against u...
ActiveModel::Errors inherits from hash and behaves unexpectedly
ActiveModel::Errors
is used to handle validation errors on Rails objects. If you inspect an instance, it feels like a hash (to be more precise, it inherits from Hash):
errors = ActiveModel::Errors.new(Object.new)
=> {}
>>
?> errors.add(:base, "foo")
=> ["foo"]
>> errors.add(:base, "bar")
=> ["foo", "bar"]
>>
?> errors
=> {:base=>["foo", "bar"]}
If you need to hack anything with these errors, beware that it behaves in a special way. If you iterate over the errors it will decompose arrays.
For ...
Making Little Classes out of Big Ones
Hashrocket Lunch n' Learn #1 with Avdi Grimm: Making Little Classes out of Big Ones
A look at the pros and cons of four different techniques for breaking a too-big class into smaller pieces.
Manually requiring your application's models will lead to trouble
In a nutshell:
If you require your Rails models manually, pay attention to the path you use. Unless you have to, don't do it at all.
Background
Consider these classes:
# app/models/user.rb
class User < ActiveRecord::Base
validate :magic
def magic
errors.add_to_base('failed') if bad_things?
end
end
^
# app/models/foo.rb
require 'user'
class Foo
# something happens here
end
Now, when your environment is booted, Rails will automatically load your models, like User
...
grosser/rspec-instafail
Show failing specs instantly. Show passing spec as green dots as usual.
Configuration:
# spec/spec.opts (.rspec for rspec 2)
--require rspec/instafail
--format RSpec::Instafail
CSS: Emulate linear gradients with inset box shadows
Why is this useful?
- You can have a background image on the same element, overlaying it with a transparent gradient.
- Since you are probably using gradients to give an element a glossy or three-dimensional feel, box shadows work much better for this. This is because linear gradients always stretch to the full size of the element (which can grow with user input), while a natural shine or shadow only highlights a fixed size on the top or bottom.
- Browser support for linear gradients is a mess. I avoid using them. In part...
CSS: Emulate borders with inset box shadows
When is this useful?
- When both parent and child elements have borders, with this technique you don't get two borders (which looks ugly). This is because child elements are rendered over inset box shadows, not inside inset box shadows.
- You want more than one border on the same element. You can have as many inset box shadows on the same element as you like, e.g. allowing you to make a picture-frame-like border.
Examples
Remember the attribute list of box-shadow
is x-offset, y-offset, blur radius, shadow r...
Automatically strip all string fields of an ActiveRecord
If your application has forms to edit string fields, you probably want to strip the entered values (remove whitespace from beginning and end). The reason is that your users will copy + paste values from unholy places (websites, Microsoft Office) and end up having trailing whitespace in most of their records.
Because browsers ignore whitespace, no one will usually notice this until you get the weirdest bug reports (e.g. two seemingly equal records are not, or multiple records for "unique" values).
Use the attached trait in your model to hav...
floere/phony
The (admittedly crazy) goal of this Gem is to be able to format/split all phone numbers in the world.
7 Ways to Decompose Fat ActiveRecord Models - Code Climate Blog
“Fat models” cause maintenance issues in large apps. Only incrementally better than cluttering controllers with domain logic, they usually represent a failure to apply the Single Responsibility Principle (SRP). “Anything related to what a user does” is not a single responsibility.
Early on, SRP is easier to apply. ActiveRecord classes handle persistence, associations and not much else. But bit-by-bit, they grow. Objects that are inherently responsible for persistence become the de facto owner of all business logic as well. And a year or tw...
RSpec: Change the type of a spec regardless of the folder it lives in
In a Rails application, *_spec.rb
files get special treatment depending on the file's directory. E.g. when you put a spec in spec/controllers
your examples will have some magic context like controller
, post
or get
that appears out of nowhere.
If you want that magic context for a spec in another folder, use the :type
option:
describe CakesController, :type => :controller do
...
end
jsTimezoneDetect
Makes a robust determination of a user's timezone through Javascript.
mattheworiordan/capybara-screenshot
Takes a screenshot when you call it, or when a test fails.
Fixing errors with state_machine when excluding states
This is for you if you get the following strange error from the state_machine
gem:
undefined method `-' for #<StateMachine::BlacklistMatcher:0x124769b0>
You probably did something like this in your state_machine ... do
block:
def self.final_states
[ :foo, :bar ]
end
transition (all - machine.final_states - [:baz]) => :target_state
Instead, define the source states like this:
def self.final_states
[ :foo, :bar ]
end
transition (all - (mach...
rails/turbolinks
Turbolinks makes following links in your web application faster. Instead of letting the browser recompile the JavaScript and CSS between each page change, it keeps the current page instance alive and replaces only the body and the title in the head.
This is similar to pjax, but instead of worrying about what element on the page to replace, and tailoring the server-side response to fit, we replace the entire body. This means that you get the bulk of the speed benefits from pjax (no recompiling of the JavaScript or CSS) without having to tail...
Literally 101 Ruby tricks
The linked slidedeck holds many tips, of which I list the most interesting to me below
DATA and END
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.
Running the attached example file data.rb
prints:
DATA is a File object to everything in the current file after "__END__"
No braces needed for 'special variables'
@instance, @@class, $global = [ 'instance', 'class', 'global' ]
puts "#@instance, #@@class, #$global"
...