Topics: Ruby

Repeats

Javascript: Compare two arrays for equality

Don't Google this, you will lose all will to live. Instead use Object#isEqual from Underscore.js:

_.isEqual([1, 2], [2, 3]) // => false

Ruby: How to camelize a string with a lower-case first letter

If you want to do JavaScript-style camelization, ActiveSupport's String#camelize method can actually help you out. Simply pass a :lower argument to it.

>> 'foo_bar_baz'.camelize
=> "FooBarBaz"
>> 'foo_bar_baz'.camelize(:lower)
=> "fooBarBaz"
Repeats

How to define constants with traits

This is pretty much like defining subclasses through traits with the Modularity gem.

module MyConstantTrait
  as_trait do
    
    self::MY_CONSTANT = 'hello universe'
    
  end
end

This would set MY_CONSTANT for any class using the trait.

Of course you can also use parameters (for logic or for setting values, like here):

module ValuesTrait
  as_trait do |*args|
    
    self::VALUES = args
    
  end
end

class Foo
  does 'values', :f...
Repeats

The Ruby Toolbox – a collection of good gems

If you need a gem for a certain purpose, be sure to check this site.


The rankings are determined by counting up the number of forks and watchers of various github projects, so I'd view it less as "this is what I should be using," and more as "these are some things I should check out." At the very least, they're all likely to be under active development and fairly up to date, and it's very useful to see groups of gems broken down by category.

Repeats

How Ruby method lookup works

When you call a method on an object, Ruby looks for the implementation of that method. It looks in the following places and uses the first implementation it finds:

  1. Methods from the object's singleton class (an unnamed class that only exists for that object)
  2. Methods from prepended modules (Ruby 2.0+ feature)
  3. Methods from the object's class
  4. Methods from included modules
  5. Methods from the class hierarchy (superclass and its ancestors)

Example

Let's say we …

Namespacing: why `uninitialized constant` error may occour in `development` but not in `test` environment

Example:

  class Book::Page
  end
  
  class MyBook < Book
    def new_page
      Page.new # has to be `Book::Page` in development to make it work 
    end
  end

Method new_page may throw an error when it was called during browser interaction in development but doesn't make the test fail.

The reason

Development autoloading isn't smart enough to find the referenced class At other environments (test, staging, production) autoloading is disabled, that all classes are already loaded when browser interaction takes place what makes …

Repeats

Do not pass an empty array to ActiveRecord.where when using NOT IN

Be careful with the Active Record where method. When you accidentally pass an empty array to the where method using NOT IN, you probably will not get what you expected:

User.where("id NOT IN (?)", [])

Even though you might expect this to return all records, this actually results in this query:

SELECT `users`.* FROM `users` WHERE (id NOT IN (NULL)) 

This will not return anything.

Repeats

How to overwrite and reset constants within Cucumber features

In order to save the original value of a constant, set the new value and restore the old value after a scenario was completed, you can use the following helper. It takes care of saving the old constant value, setting the new one without throwing warnings and resets the value with an After hook.

This module also enables you to introduce new global constants. Since these newly defined constants do not have any value to be reset to, they simply are deleted (remove_const) once the respective Cucumber step finishes.

You can copy the file at…

External content

Why Ruby Class Methods Resist Refactoring

In a nutshell:

  • Splitting a long method into sub methods is easier in instances since it is in classes. Since you must not save state in a class, you need to pass around context as a long chain of parameters again and again.
  • If your public API has a single entry point, you can still have a class-level method that takes care of constructing the instance etc. So it's all win.
Repeats

Know the side effects of using hashes for conditions

Find conditions for scopes can be given either as an array (:conditions => ['state = ?', 'draft']) or a hash (:conditions => { 'state' => 'draft' }). Each of these options has considerable side effects you should know about. This applies to both Rails 2 and old patch levels of Rails 3. The issue is fixed in Rails 3.0.5, has been re-introduced in Rails 3.2 and has been fixed again in Rails 4. If you're using our Rails 3.x forks you are not affected. If you are using Rails 2.3.x you are always affected, even if you are using our forks …

String#indent: Know your definitions!

String#indent is not a standard Ruby method. When you use it, be sure to know where this method comes from. Many Gems shamelessly define this method for internal usage, and you'll never know when it may be removed (since it's usually not part of the Gem's API).

Unless you're using Rails 4 (which brings String#indent in ActiveSupport), you'll be best of defining it yourself. This card has it for you.

Gems that define String#indent (incomplete) —————————-…

Repeats

Namespacing controller classes without affecting routes

When you want to namespace your controller classes (group some controllers into a folder) but leave the corresponding routes unaffected, you can use the scope method like follows:

scope module: 'proxy' do
  resources :properties
end
Repeats

How to stub class constants in RSpec

Hint: There's another card with this helper for Cucumber features.


Sometimes you feel like you need to stub some CONSTANT you have defined in an other class. Since actually constants are called constants because they're constant, there's no way to easily stub a constant.

Here are three solutions for you.

Easiest solution

Rethink! Do you really need CONSTANT = %w[foo bar] to be constant? In many cases, setting it as a sim…

Repeats

Test if two date ranges overlap in Ruby or Rails

A check if two date or time ranges A and B overlap needs to cover a lot of cases:

  • A partially overlaps B
  • A surrounds B
  • B surrounds A
  • A occurs entirely after B
  • B occurs entirely after A

One trick to cover all these cases with a single expression is to see if the start date of each range is looking at the end date of the other range in the same direction.

The code below shows how to implement this in Ruby on Rails. The example is a class Interval, which has two attributes #start_date and #end_date. These dates are considere…

External content

Thread Safety With Ruby — Luca Guidi

Ruby’s model for concurrency is based on threads. It was typical approach for object oriented languages, designed in the 90s. A thread is sequence of instructions that can be scheduled and executed in the context of a process. Several threads can be running at the same time.

Ruby’s VM process allocates a memory heap, which is shared and writable by threads. If incorrectly coordinated, those threads can lead to unexpected behaviors.

External content

Ruby on Rails 4 and Batman.js

Batman is an alternative Javascript MVC with a similar flavor as AngularJS, but a lot less features and geared towards Ruby on Rails.

The attached link leads to a tutorial for a small blog written with Rails / Batman.js.

I'm collecting other Batman.js resources in my bookmarks.

Repeats

Finding a method name on any Ruby object

Wondering how a specific method on an object is exactly named? You can use Enumerable#grep to detect it in the array of methods.

@user.methods.grep /name/ # => [:name, :first_name, :last_name]

You can also call #private_methods or #public_methods.

If you call #methods(false) you only get methods defined on the object's class directly, but not methods inherited from superclasses.

How to call overwritten methods of parent classes in Backbone.js

When you are working with Backbone models and inheritance, at some point you want to overwrite inherited methods but call the parent's implementation, too.
In JavaScript, there is no simple "super" method like in Ruby – so here is how to do it with Backbone.

Example

BaseClass = Backbone.Model.extend({
  initialize: function(options) {
    console.log(options.baseInfo);
  }
});

MyClass = BaseClass.extend({
  initialize: function(options) {
    console.log(options.myInfo);
  }
});

...
403 cards