Posts Tagged ‘rails views’

integer range collection_select form helper

<%= f.collection_select :priority, (1..5), :to_i, :to_i %>

checking for local variables in rails partials

# You cannot test whether a certain key
# (:somevar) was present in the locals
# hash passed to render using

defined?(:somevar),

# due to the way template compilation works in Rails.
# But you can use the following pattern instead:

local_assigns.include?(:somevar)

layout possibilities in rails

Layouts in rails can be accomplished in quite a few ways. Here are the most common:

  • layouts/application.html.erb #default for all controllers
  • layouts/my_controller.html.erb #layout for a controller with the same name
  • layout "my_layout" in controller # explicitly set layout in controller
  • layout :decide_on_layout # with ‘decide_on_layout being a method returning a layout name as string
  • render :layout => false # no layout at all
  • render :partial => ‘my_partial’, :layout => ‘my_other_partial’ # partials as layouts

clean page titles (from Ryan Bates’ screencasts)

# application_helper.rb

def title(page_title)
content_for :title { page_title }
end

# e.g. show.html.erb

<% title "overidden title" %>
...

# layouts/some_layout.html.erb

<%= yield(:title) %>

<%= yield %>

blog archive helper

# ------------------------------------------
#                 routes.rb
# ------------------------------------------

# show posts by date
map.connect ':year/:month/:day',
  :controller => 'posts',
  :action => 'index',
  :year => /\d{4}/,
  :month => /\d{1,2}/,
  :day => /\d{1,2}/

# show posts by month
map.connect ':year/:month',
  :controller => 'posts',
  :action => 'index',
  :year => /\d{4}/,
  :month => /\d{1,2}/

# ------------------------------------------
#            post_controller.rb
# ------------------------------------------

def index
  if params[:year] && params[:month]
    datestring = "#{params[:year]}-#{params[:month]}"
    datestring << "-#{params[:day]}" if params[:day]
      @posts = Post.find_all_by_date_like(datestring)
    else
      @posts = Post.find(:all)
    end

    respond_to do |format|
      format.html # index.html.erb
      format.xml  { render :xml => @posts }
      format.atom
    end
  end
end

# ------------------------------------------
#          post.rb
# ------------------------------------------

class Post < ActiveRecord::Base
  class << self
    def find_all_by_date_like(datestring)
      self.find(:all, :conditions => ['created_at LIKE ?', datestring + '%'])
    end
  end
  #...
end

# ------------------------------------------
#          application_helper.rb
# ------------------------------------------

MONTHS =
  [
    'January', 'February', 'March', 'April', 'May', 'June',
    'July', 'August', 'September', 'October', 'Novemeber', 'December'
  ]

def archive_content(posts)
  raise ArgumentError unless block_given?
  with_unique_dates_from_resource posts do |year, month|
    link_name = "#{MONTHS[month.to_i - 1]} #{year}"
    yield(link_to(link_name, "/#{year}/#{month}"))
  end
end

def with_unique_dates_from_resource(resource, timestamp = :created_at, find_options = {})
  if resource.is_a?(Array)
    collection = resource
  else
    proxy = resource.to_s.singularize.camelcase.constantize
    collection = proxy.find(:all, find_options)
  end
  collection.map do |model|
    model.send(timestamp).strftime("%Y/%m")
  end.uniq.each do |date|
    dates = date.split('/')
    yield(*dates)
  end
end

# ------------------------------------------
#               in some view
# ------------------------------------------

<% archive_content :posts do |archive_link| %>
  • <%= archive_link %>
  • <% end %> # or <% archive_content Post.find(:all) do |archive_link| %>
  • <%= archive_link %>
  • <% end %>

    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