King of Nothing, the DCI paradigm is a scam
I’ve worked on huge applications in Ruby and Rails before. I very much want to believe in DCI, but I’m having a hard time accepting the promises of Clean Ruby when it seems like the work on this paradigm is half-done. If it weren’t so oversold and hyped, I think I’d be more patient, but right now I’m just frustrated and confused.
randym/axlsx · GitHub
Axlsx is an incredible gem to generate "Office Open XML" spreadsheet files (XLSX). Does not break on large spreadsheets and supports a ton of features like graphs.
API looks mature and existing code is easy to migrate when coming from the spreadsheet
gem.
The documentation of some methods is a bit out of date, but you'll find your way around the gem's code.
No support for reading files, however. :( If you want to open XLSX spreadsheets (for example to confirm your output in tests), you can use [roo
](h...
Helper methods - RSpec Core
You can define methods in any example group using Ruby's def
keyword or define_method
method. These helper methods are exposed to examples in the group in which they are defined and groups nested within that group, but not parent or sibling groups.
Everything you ever wanted to know about constant lookup in Ruby
If you ever wondered why a constant wasn't defined or wasn't available where you expected it to be, this article will help.
Also see Ruby constant lookup: The good, the bad and the ugly.
Cronjobs: "Craken" is dead, long live "Whenever"
Our old solution for cronjobs, the "craken" plugin, is no longer maintained and does not work on Rails 3.2+.
We will instead use the whenever gem.
"Whenever" works just like "craken", by putting your rake tasks into the server's cron table. Everything seems to work just like we need it.
Installation for new projects
-
Add "whenever" to your
Gemfile
:group :deploy do gem 'whenever', require: false end
-
Add it to your
config/deploy.rb
:
...
navy gem: Hide empty navigation bars
navy 0.5.1+ gives empty navigation containers a CSS class .navy-empty
which you can hide via
.navy-navigation
&.navy-empty
display: none
SearchableTrait is now a gem: Dusen
For two years we've been using SearchableTrait
which gives models the ability to process Googlesque queries like this:
Contact.search('a mix of words "and phrases" and qualified:fields')
This trait used to be a huge blob of code without tests and documentation, so I made a gem out of it. Check out https://github.com/makandra/dusen for code, tests, and a huge README.
You should use the Dusen gem and delete SearchableTrait
in all future projects.
Note that the syntax to define query proc...
byebug / ruby-debug: Find out current debugger position
So you are debugging like a boss and lost track of where you actually are in your code? No problem:
- Calling "
l=
" will show you the current file and line. That's a lower-caseL
and an equals sign. - "
where
" (or "backtrace
") will give you the debugger call stack, including current file and line as well. It can be quite long.
Zeus promises to make rails development faster
I am talking about development speed. When your application starts growing and you start adding gems, it starts to take really long to start up, be it the server, console or just running a single spec.
Zeus is smart, you don’t have to put it in your Gemfile or run it with Bundler, all you need to do is create a JSON config file via
zeus init
and then start the serverzeus start
.
After that, you’re ready to go, all you need to do is prefix every command with zeus. That means
rails server
becomeszeus server
, `rails console...
Capybara 2.0 has been released
The gem author Jonas Nicklas highlights in a Google Groups post that the release
- is not backwards compatible to 1.x versions of Capybara
- does not support Ruby 1.8.x anymore
- removes confusion with Rails' built in integration tests (you put capybara rspec integration tests into the
spec/feature/...
folder) and the:type
metadata has been changed from:request
to:feature
- throws exceptions when trying to interact with an element whose identifier is...
Andand and SimpleDelegator
The very useful andand gem does not play very nice with Ruby's SimpleDelegator (or vice versa).
This following will not work:
class MyDecorator < SimpleDelegator
def foo
end
end
MyDecorator.new(Object.new).andand.foo
The reasons are a bit subtle, basically SimpleDelegator will "force" some methods to be delegated, so the andand
method is called on the wrapped object, not the delegator.
You can fix it like this:
class Decorator < SimpleDelegator
def an...
Using sets for many-to-many relationships
A technique to vastly reduce the number of join model records that need to be stored in the database.
The technique is only effective when there is a high redundancy in your data, e.g. combinations of the same 20 tags are used to label thousands of books.
The technique is also limited in that your join models cannot have additional logic, such as attributes or callbacks.
Ther has-many-with-set gem is an implementation of this technique.
uninitialized constant MysqlCompat::MysqlRes (NameError)
If you get a stacktrace complaining about uninitialized constant MysqlCompat::MysqlRes
a system library update might broke your gem.
You might have switched from MySQL to MariaDB, but forgot to rebuild your MySQL gems.
Try fully removing and re-installing the gem:
gem uninstall mysql mysql2
bundle install
Rails: When to use :inverse_of in has_many, has_one or belongs_to associations
When you have two models in a has_many
, has_one
or belongs_to
association, the :inverse_of
option in Rails tells ActiveRecord that they're two sides of the same association.
Example with a has_many
/ belongs_to
association:
class Forum < ActiveRecord::Base
has_many :posts, inverse_of: :forum
end
class Post < ActiveRecord::Base
belongs_to :forum, inverse_of: :posts
end
Knowing the other side of the same association Rails can optimize object loading so forum
and forum.posts[0].forum
will reference the same o...
Capybara: evaluate_script might freeze your browser
Capybara gives you two different methods for executing Javascript:
page.evaluate_script("$('input').focus()")
page.execute_script("$('input').focus()")
While you can use both, the first line (with evaluate_script
) might freeze your browser window for 10 seconds.
The reason is that evaluate_script
will always return a result. The return value will be converted back to Ruby objects, which in case of complex objects (e.g. a jQuery collection) is very expensive.
Because of this we recommend to only use evaluate_script
whe...
Rubygems: Rebuild native extensions
Rarely, you might want to rebuild all gems with native extensions, because they might be compiled against outdated system libraries, resulting in some warnings or even segfaults or other ruby errors.
You can do that using
gem pristine --all
This will reset all gems to a pristine state as if you'd reinstall them, and as a side effect, rebuild all native extensions.
The above command will also help you sorting out errors like this after a distribution upgrade:
libmysqlclient_r.so.16: cannot open shared object file: No such fil...
Waiting for page loads and AJAX requests to finish with Capybara
If you're using the Capybara webdriver, steps sometimes fail because the browser hasn't finished loading the next page yet, or it still has a pending AJAX request. You'll often see workarounds like
When I wait for the page to load
Then ...
Workarounds like this do not work reliably, will result in flickering tests and should be avoided. There is no known reliable way to detect if the browser has finished loading the page.
Solution
Instead you should wait until you can observe the result of a page load. E.g. if y...
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/
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...
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
...
floere/phony
The (admittedly crazy) goal of this Gem is to be able to format/split all phone numbers in the world.
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...