Sunday, March 23, 2014

Handy enhancement for ruby String: Defaults to default text

In my code , I repeat a lot this pattern: if the string is blank / empty, return a default text, otherwise return the original text.

final_text = text.blank? ? "default text" : text content_tag :h1, text.blank? ? "default text" : text, :class => 'mega'


I discovered this little gem in Stackoverflow (I lost the original source), you only need to reopen the String class, in an intializer, or decorator.

class String

  def defaults_to(what)
    self.strip!
    self.blank? ? what : self
  end


end

and, now you can use it in a readable form

text.defaults_to("default text")


Saturday, March 1, 2014

Concerns in Rails (or how to reuse code)

I have been doing some experiments with rails Concerns . While they have been widely publicited for Rails 4, you can use them in Rails 3 as well.

They are like the ruby standard include / extend pattern, but taking care of dependencies. In any case it would be easy to go back to the 'raw' include / exclude game.

This is an example of how to use them.

 require 'active_support/concern'

module Concerns

  module DummyConstants

  end

  module Dummy
    extend ActiveSupport::Concern

    #it seems that things declared here are shared between all inclusions (saving memeory)
    SEXY_REGEXP = /SEXY_REGEXP/i
    MEM_HOGGING = Array.new(1024 * 1024)
    MEMBERSHIP_STATUSES = %w(accepted invited requested rejected_by_group rejected_group)

    included do
      #The included block will be triggered at inclusion time
      before_create :stuff_on_creation

      attr_accessor :accesor_for_the_instance
      class << self
        attr_accessor :accesor_for_the_class
      end

    end

    module ClassMethods
      #Methods in ClassMethods will get added class methods
      def dummy?
        puts "\nCLASS dummy? called\n"
        true
      end

    end

    #these methods are added as instance methods

    def dummy?
      puts "\nINSTANCE dummy? called\n"
      true
    end

    def stuff_on_creation
      puts "\ncreation called\n"
    end

  end


end


Just create a file under model/concerns/dummy.rb and include it

User.send :include, Concerns::Dummy

or

class User
 include Concerns::Dummy end

Note that I repeat the namespace Concerns, but in other examples found in internet people dont. Rails 4 has included models/concerns and controllers/concerns in the autoload paths and in Rails 4 it would work without the namespace. In Rails 3, you need to add the namespace OR using some trick.

I find easier to understand if I include the 'Concern', tough.

Profit!