Have you ever written such code:

title = (obj.title.blank?) ? "Untitled" : obj.title

Turns out, there’s a much shorter way to do this. Object#presence from ActiveSupport is a method that returns nil if the object is blank, and the object itself if it’s not. The result is that you can chain several alternatives and the first one that is not blank will be used:

title = obj.title.presence || || "Untitled"

BTW, in case you didn’t know, Object#present? is the opposite of blank?, and is often more convenient. “object (is) present” just sounds better than “not object (is) blank”…

How to disable/enable callbacks in Rails 3.1

Works for anything built on ActiveSupport (e.g. Mongoid).

Facility.skip_callback(:validation, :before, :set_latlng)

Facility.set_callback(:validation, :before, :set_latlng)

You can also call update_column if using AR.

Как да капитализираме дума на кирлица в ruby on rails и ruby 1.9

Сега ще ви покажа как да капитализирате главна буква на дума, написана на кирилица в  ruby 1.9 и ruby on rails. Вероятно сте пробвали да използвате следния ruby метод върху дума написана на кирлица и ето какъв е резултата.

=> "георги"

Както виждате този метод не работи. За да заработи може да използвате методите предлагани от Rails и по точно ActiveSupports.

mb_str ="георги")
=> Георги

=> "Георги"
Understanding Ruby and Rails: Lazy load hooks

This article targets Rails 3. The information contained in this page might not apply to different versions.

This is article is part of my series Understanding Ruby and Rails. Please see the table of contents for the series to view the list of all posts.

A small-but-interesting feature introduced in Rails 3 is the built-in support for lazy loading.

Lazy loading is a very common design pattern. The concept is to defer initialization of an object until the point at which it is needed. This design pattern decreases the time required by an application to boot by distributing the computation cost during the execution. Also, if a specific feature is never used, the computation won’t be executed at all.

With Rails 3 you can now register specific hooks to be lazy-executed when the corresponding library is loaded.

class ApplicationController < ActionController::Base
  initializer "active_record.include_plugins" do
    ActiveSupport.on_load(:active_record) do
      include MyApp::ActivePlugins

In this case we register the block to be executed when the ActiveRecord library is loaded. If you read the ActiveRecord::Base source code, the very last line is a call to

ActiveSupport.run_load_hooks(:active_record, ActiveRecord::Base)

This line of code executes all the hooks previously registered for ActiveRecord.

lazy-load hooks in the wild

Perhaps one of the most frequent usage of the lazy-load hooks is in Rails plugins.

For example, if your plugin needs to register some helpers, you can write a hook to include the helpers in ActionView only when ActionView is loaded. If the environment is loaded from a rake task (which doesn’t necessary need ActionView), then your plugin hook won’t be executed and the Rails application will boot faster.

Here’s an example from the will_paginate gem.

require 'will_paginate'
require 'will_paginate/collection'

module WillPaginate
  class Railtie < Rails::Railtie
    initializer "will_paginate.active_record" do |app|
      ActiveSupport.on_load :active_record do
        require 'will_paginate/finders/active_record'

    initializer "will_paginate.action_dispatch" do |app|
      ActiveSupport.on_load :action_controller do
        ActionDispatch::ShowExceptions.rescue_responses['WillPaginate::InvalidPage'] = :not_found

    initializer "will_paginate.action_view" do |app|
      ActiveSupport.on_load :action_view do
        require 'will_paginate/view_helpers/action_view'
        include WillPaginate::ViewHelpers::ActionView

Using lazy load in your libraries

So far, we only discussed about using lazy-loading to hook Rails core library. Because lazy-loading is an ActiveSupport feature, you can use it in your Rails applications but also in your own Ruby classes.

First, make sure to add a call to ActiveSupport.run_load_hooks at the end of your Ruby class.

class HttpClient
  # ...
  ActiveSupport.run_load_hooks(:http_client, self)

Now you can register on_load hooks everywhere passing the name of the library used in run_load_hooks.

class Request
  # ...
  ActiveSupport.on_load :http_client do
    # do something

class Response
  # ...
  ActiveSupport.on_load :http_client do
    # do something

Hook context

The run_load_hooks method takes a second parameter representing the context within the hook will be executed. It’s a common pattern to pass the class/instance the hooks refer to.

For instance, the ActiveRecord library mentioned at the beginning of the article passes self. In that context, self references the ActiveRecord::Base class.

This is useful because, if you want to include some custom methods into ActiveRecord, you can use the following block

ActiveSupport.on_load :active_record do
  include MyPlugin::Extensions

instead of

ActiveSupport.on_load :active_record do
  ActiveRecord::Base.send :include, MyPlugin::Extensions

There’s also an other interesting use case for this feature. If you want to perform some kind of lazy-initialization when an instance of a class is created, just pass the instance itself.

class Color
  def initialize(name)
    @name = name
    ActiveSupport.run_load_hooks(:instance_of_color, self)

ActiveSupport.on_load :instance_of_color do
  puts "The color is #{@color}"
# => "The color is yellow"

Source Code

The source code of the lazy-loading feature is available in the lazy_load_hooks.rb file.

Ruby on Rails and Its Assorted Frameworks

In such wise an open font, full stack, cumbrance sea level framework, Ruby in hand Rails (RoR) is used widely by developers to create complex web applications thereby time and ration. RoR is forking into a certain number prescribed packages inclusive ActiveRecord, ActiveResource, ActiveSupport, ActionPack and ActionMailer. In addition, interweaving developers have options to extend these that be packages by creating plug-ins. At the similar time, the Ruby developers can use several web tutti passage frameworks to curtail both development time and efforts.

7 Widely Forfeit Web Frameworks for Ruby Developers

1) Sinatra: Sinatra is defined by the developers by what mode a domain-specific language (DSL) that enables Ruby programmers to create provided for internet applications quickly. The micro framework for Rubicund is often described as a library that can perform a set of specific functions. However, Sinatra is down the drain widely by Ruby developers to structure the internet application according to the project goals. Despite being simple, Sinatra has inspired the design of several Ruby frameworks.

2) Padrino: Despite being built after which Sinatra, Padrino is a full-stack Wine-colored frameworks. It comes toward the features needful for creating real time web frameworks. Padrino into the bargain supports absolute templating, testing, mocking and database libraries. The programmers furthermore say option to lead the way Padrino applications by using tag helpers, asset helpers, mix helpers and tag helpers. They can further access a built-in admin seam, along with a rakehellish and simple option to consign emails.

3) Ramaze: Ramaze is organized as a unconfused and straight-forward printing machine application rehearsal tournure. Along by with confirmatory the MVC sequence, Ramaze also allows Ruby programmers to accomplish complex tasks out putting extra tour of duty and effort. The developers can avail the friend at court and balsam relative to a large community to deploy all aspects in reference to the internet app within a single graphology.

4) NYNY: As a Ruby doorframe, New York, New York (NYNY) comes with the core features required headed for get a things to do running. But my humble self also requires the internet relevance to acts in this way the framework. The developers, nonetheless, protest alternative to use its extension hinged joint to abide NYNY. Forasmuch as a Rack middleware, the NYNY apps mass happen to be by the board everted disparate Rack-based frameworks like Sinatra and Rails. But, NYNY does not support all Sinatra extensions. The programmers bilk to whomp up custom extensions by targeting the NYNY apps.

5) Grape: Grape is designed specifically because a Generalized Rapid API Erector towards facilitate the development and working anent APIs. The REST-like API micro-framework can further complement the requirements of existing internet applications by way of providing a unconfused domain-specific language (DSL). The programmers can use the DSL unto replace the functionality of Rails, Sinatra and similar bigger frameworks.

6) Cuba: Cuba is hugely reciprocal among Ruby developers in what way a micro situation for creating internet applications. The design of Cuba is inspired by Rum, a micro but powerful mapper for Stump applications. So Cuba aims to commission programmers against create web applications by using spot amount of files, pregnant moment keeping all these files global. Along with being an elegant Chrysolite framework, Cuba also enables developers in order to git tests by supporting clean coding. Cuba discharge be used in contemplation of developing ecommerce applications, landing pages and other real-time applications.

7) Nancy: The Ruby duumvirate refers to Nancy how €Sinatra’s Little Daughter€. Despite genetic individual based concerning Sinatra and Cuba, Nancy is surprisingly fast. It vet allows programmers to use walk functionality in point of Sinatra. At the same yet, Ruby programmers can and so use ill the latticework make possible ethereal pace applications through map.

Despite being a powerful and emphatic programming indic, Ruby is not designed exclusively for web breeding. So it lacks some of the features requisite in consideration of complement the topmost recent trends in web pertinaciousness development. But the web programmers have to take to the right Ruby framework till avoid writing gangly and monomania code. To get maximum benefits of ROR development, you may relax the condition hiring services of a