Posts Tagged ‘rails helper’

aligned numbers aka zerofill

# zerofill(7,3) => "007"
def zerofill(value, digits = 9)
"%0#{digits}d" % value.to_i
end

google analytics for rails production environment

# assuming a partial located in views/shared
# that contains the google analytics script body
def render_google_analytics_script
  render :partial => "/shared/google_analytics" if Rails.env == "production"
end

# render from layouts
<%= render_google_analytics_script %>

paginated record numbers

# application_helper.rb
# record numbering inside paginated admin index views
def paginated_record_number(offset)
  # TODO find out will_paginate page_count query
  page = params[:page] ? params[:page].to_i : nil
  (page ? page - 1 : 0) * ( params[:per_page] || 30) + offset + 1
end

# use in views like so
<%= paginated_record_number(idx) %>

link_to_has_one

# Creates 'Show AssociatedResource' or 'New AssociatedResource' links
# based on wether the specified has_one association exists or not.
# The optional options parameter is passed through to link_to as html_options.
# Since this helper relies on record identification, there is no way to pass
# all the other url_for options, as far as I can see
# ---------------------------------------------------------------------------
# Use in your views like so:
# <%= link_to_has_one @post, :comment %>
# <%= link_to_has_one @post, :comment, "What say you?" %>
# <%= link_to_has_one @post, :comment, "What say you?", :class => "oldskool" %>
def link_to_has_one(parent, has_one_association_name, options = {})
  has_one_association_name = has_one_association_name.to_s.underscore
  child = has_one_association_name.camelize
  child_path = "#{parent.class.to_s.underscore}_#{has_one_association_name}_path"
  if parent.send(has_one_association_name)
    name = options[:new_name] ? options[:new_name] : "Show #{child}"
    link_to name, self.send(child_path, parent), options
  else
    name = options[:existing_name] ? options[:existing_name] : "New #{child}"
    link_to name, self.send("new_#{child_path}", parent), options
  end
end

watching activerecord

# This greatly helps learning what ActiveRecord does!

# All credits go to Jamis Buck at
# http://weblog.jamisbuck.org/2007/1/31/more-on-watching-activerecord

# environment.rb
def log_to(stream)
  ActiveRecord::Base.logger = Logger.new(stream)
  ActiveRecord::Base.clear_active_connections!
end

# in irb or script/console or environment.rb
log_to(STDOUT)

# or create new streams
buffer = StringIO.new
log_to(buffer)
puts buffer.string

a monkey’s stylable button_to

  def button_to(name, options = {}, html_options = {}, additional_content = "", descriptor_container = :span)

    html_options = html_options.stringify_keys
    convert_boolean_attributes!(html_options, %w( disabled ))

    method_tag = ''
    if (method = html_options.delete('method')) && %w{put delete}.include?(method.to_s)
     method_tag = tag(
       :input,
       :type => 'hidden',
       :name => '_method',
       :value => method.to_s
     )
    end

    form_id = (f_id = html_options.delete('form_id')) ? "id='#{f_id}'" : ""
    form_method = method.to_s == 'get' ? 'get' : 'post'

    request_token_tag = ''
    if form_method == 'post' && protect_against_forgery?
     request_token_tag = tag(
       :input,
       :type => "hidden",
       :name => request_forgery_protection_token.to_s,
       :value => form_authenticity_token
     )
    end

    if confirm = html_options.delete("confirm")
     html_options["onclick"] = "return #{confirm_javascript_function(confirm)};"
    end

    url = escape_once(options.is_a?(String) ? options : self.url_for(options))
    name ||= url

    descriptor = content_tag(descriptor_container.to_s, name, html_options)

    button_options = { "name" => "#{name.underscore}", "value" => name }
    button_id = html_options.delete("button_id")
    button_type = html_options.delete("button_type")
    button_options.merge!("id" => button_id) if button_id
    button_options.merge!("type" => button_type) if button_type

    form =  "
” form << "
” form << " #{method_tag}" form << " #{request_token_tag}" form << " #{content_tag("button", descriptor, button_options) }" form << "
” form << additional_content form << "
” form end

polymorphic link_to

# Why didn't I try out earlier if this is possible? Well, it is!

<%= link_to("Show", [ @foo, @bar ]) %>

time formatting (from Ryan Bates’ screencasts)

# in views

<%= post.created_at.to_s(:my_cool_format) %>

# in environment.rb (or any rb file under 'config/initializers' if using rails 2.0)

Time::DATE_FORMATS[:my_cool_format] = "due at %B %d on %I:%M %p"

one line client block helpers for rails views

# somewhere in a view
<%= one_line_block_helper books, binding %>

# somewhere in a helper
def one_line_client_block_helper(some_collection, erb_binding)
  concat("
    “, erb_binding) show_some_collection(some_collection) do |item| concat(”
  • #{item.name}
  • “, erb_binding) end concat(”
“, erb_binding) end # of course this can be used separately like every block helper def show_some_collection(some_collection) # this can get arbitrarily complex some_collection.each do |item| yield item end end

recursive rails view helper that prints a tree

def display_tree_recursive(tree, parent_id)
  ret = "\n
    ” tree.each do |node| if node.parent_id == parent_id ret += “\n\t
  • ” ret += yield node ret += display_tree_recursive(node.children, node.id) { |n| yield n } unless node.children.empty? ret += “\t
  • \n” end end ret += “
\n” end def print_path_to_node(node, separator) path = “” path += print_path_to_node(node.parent, separator) { |n| yield n } unless node.parent.nil? path += yield node path += separator unless node.children.empty? return path end