Reusable code snippets

Hello Everyone, I have reviewed my application and extracted out few methods, which we can reuse in other applications if required.

To normalize url

def normalize\_url(url)
  url = url.strip
  /^http/.match(url) ? url : "http://#{url}"
end

Display image and default image if image is breaking

def display\_image(object)
  default\_image = "/assets/default_image.jpg"
  on\_error\_pic  = "this.onerror=null;this.src='"+ default\_image +"';"
  image\_tag object.pic.url(:style), alt: "", onerror: on\_error\_pic
end

Time in HH:MM:SS format

def time\_in\_hhmmss(time)
  Time.at(time).utc.strftime("%H:%M:%S")
end

To highlight current tab(helper method)

def is\_active(controller)
  @active ||= { params[:controller] => 'active' }
  @active[controller]
end

To show flash messages with bootstrap

ALERT\_TYPES = [:error, :info, :success, :warning]

def bootstrap\_flash
  flash\_messages = []
  flash.each do |type, message|
    next if message.blank?
    type = message\_type(type)
    next unless ALERT\_TYPES.include?(type)
    Array(message).each do |msg|
      text = content\_tag(:div,
        content\_tag(:button, "x", class: "close", "data-dismiss" => "alert") +
        msg.html_safe, class: "alert fade in alert-#{type}")
      flash\_messages << text
    end
  end
  flash\_messages.join("\n").html_safe
end

def message\_type(type)
  type = :success if type == :notice
  type = :error if type == :alert
  type
end

To show device error messages with bootstrap

def devise\_error\_messages!
  return '' if resource.errors.empty?
  messages = resource.errors.full_messages.map { |msg| content\_tag(:li, msg) }.join
  sentence = I18n.t('errors.messages.not_saved',
    count: resource.errors.count,
    resource: resource\_class.downcase)
  html= content\_tag(:div, 
    content\_tag(:button, "x", class: "close", "data-dismiss" => "alert") +
    content\_tag(:h4, "#{sentence}") + "#{messages}",
    class: "alert alert-error alert-block")
end

Format phone number in (012) 345-6789 format

def format\_phone\_number(number)
  if (number && number =~ /^\d{10}$/ && number.to_i >= 999999999)
    number =[(#{number[0..2]}) #{number[3..5]}-#{number[6..-1]}"
  end
  number
end

Note - [Active Record Observer][1] has been removed from Rails 4, we can use [Active Record Concern.][2]

Thanks
[1]: http://api.rubyonrails.org/v3.2.13/classes/ActiveRecord/Observer.html
[2]: http://api.rubyonrails.org/classes/ActiveSupport/Concern.html

Sunil Sharma

I am a Ruby on Rails developer, passionate about building interesting and innovative web and mobile apps. | Ruby on Rails | Ember.js | Cordova | Travelling | Party | Trekking ...

Read More