Friday, May 30, 2014

Notes - Rails Tutorial Chapter 5 - REST

REST architecture
wiki defines REST as:
Representational state transfer (REST) is a software architectural style consisting of a coordinated set of architectural constraints applied to components, connectors, and data elements, within a distributed hypermedia system.

What???
As condescending as this is it is also a helpful explanation:
http://katgleason.tumblr.com/post/37836552900/how-i-explained-rest-to-my-wife

https://www.servage.net/blog/2013/04/08/rest-principles-explained/

http://rest.elkstein.org/

http://www.railstutorial.org/book/demo_app#table-demo_RESTful_users
HTTP requestURLActionPurpose
GET/usersindexpage to list all users
GET/users/1showpage to show user with id 1
GET/users/newnewpage to make a new user
POST/userscreatecreate a new user
GET/users/1/editeditpage to edit user with id 1
PATCH/users/1updateupdate user with id 1
DELETE/users/1destroydelete user with id 1

Vim vs Sublime

I  decided to try out Sublime finally. I am a gvim user right now and am very happy using it. Because I am going to be pair programming this summer with 2 people who use Sublime I figured that I should get a head start on learning it.  I downloaded the version for Linux Ubuntu and am working on setting it up. I found this tutorial to help me get it rolling.
How to install Sublime Text on Ubuntu tutorial.

Thursday, May 29, 2014

Notes - Rails Tutorial Chapter 7

== === eq? equal? 
http://stackoverflow.com/questions/7156955/whats-the-difference-between-equal-eql-and

Db:rest
Josh found:

http://stackoverflow.com/questions/10301794/difference-between-rake-dbmigrate-dbreset-and-dbschemaloadhttp://rake.rubyforge.org/

Rails comes equipped with three environments: test, development, and production. The default environment for the Rails console is development:

If you ever need to run a console in a different environment (to debug a test, for example), you can pass the environment as a parameter to the console script:

  $ rails console test

As with the console, development is the default environment for the local Rails server, but you can also run it in a different environment:

  $ rails server --environment production
If you view your app running in production, it won’t work without a production database, which we can create by running rake db:migrate in production:

  $ bundle exec rake db:migrate RAILS_ENV=production

REST!!!!!
POST, GET, PATCH, and DELETE
When following REST principles, resources are typically referenced using the resource name and a unique identifier.

show when Rails’ REST features are activated, GET requests are automatically handled by the show action.
HTTP requestURLActionNamed routePurpose
GET/usersindexusers_pathpage to list all users
GET/users/1showuser_path(user)page to show user
GET/users/newnewnew_user_pathpage to make a new user (signup)
POST/userscreateusers_pathcreate a new user
GET/users/1/editeditedit_user_path(user)page to edit user with id1
PATCH/users/1updateuser_path(user)update user
DELETE/users/1destroyuser_path(user)delete user
______________________________________________________________________________________________________________________________________________________________________

Here we’ve used params to retrieve the user id. When we make the appropriate request to the Users controller, params[:id] will be the user id 1, so the effect is the same as the find method
@user = User.find(params[:id])
User.find(1)
Technically, params[:id] is the string "1", but find is smart enough to convert this to an integer.

Factory Girl is a DSL for defining Active Record objects.

Monday, May 26, 2014

Notes - Rails Tutorial Chapter 4

This is a great "Intro to Ruby" chapter. It is really helpful to follow along with the Rails Console just to get used to using it.

The map method returns the result of applying the given block to each element in the array or range.

   I wish this was worded better
4.3.3 Hashes and symbols
Hashes are essentially arrays that aren’t limited to integer indices. (In fact, some languages, especially Perl, sometimes call hashes associative arrays for this reason.) Instead, hash indices, or keys, can be almost any object.
Very cool
 flash = { success: "It worked!", error: "It failed." }
 flash.each do |key, value|
   puts "Key #{key.inspect} has value #{value.inspect}"
 end
methods
  inspect
  p - p returns the object being printed while puts always returns nil
  map
  second - a rails method
  Hash merge http://www.ruby-doc.org/core-2.1.2/Hash.html#method-i-merge

strings vs. hashes
strings need to be compared character by character, while symbols can be compared all in one go.

When hashes are the last argument in a function call, the curly braces are optional
Exercises



Create three hashes called person1, person2, and person3, with first and last names under the keys :first and :last. Then create a params hash so that params[:father] is person1, params[:mother] is person2, and params[:child] is person3. Verify that, for example, params[:father][:first] has the right value.

instance method
A method called on an instance, such as length, is called an instance method.

class method
When a method gets called on the class itself, as in the case of new, it’s called a class method

Wednesday, May 21, 2014

Wednesday, May 14, 2014

struct

http://www.ruby-doc.org/core-2.1.1/Struct.html
A Struct is a convenient way to bundle a number of attributes together, using accessor methods, without having to write an explicit class. 
The Struct class generates new subclasses that hold a set of members and their values. For each member a reader and writer method is created similar to Module#attr_accessor.

Ruby Lesson - 1

Kurtis had me set up a directory with a file structure.

tyson
  L  bin
      lib
        L  tyson.rb
      spec
     
      tmp
      Gemfile
      Gemfile.lock
      Rakefile
      .gitignore

spec/spec_helper.rb
require "tyson"

Gemfile
#!/usr/bin/env
source "https://rubygems.org"

ruby "2.1.1"

gem "pry"
gem "pry-doc"
gem "rspec", "3.0.0.beta2"
gem "rake"
gem "yard"


Rakefile

#!/usr/bin/env rake

require "rspec/core/rake_task"
require "yard"

desc "Run all the tests in spec"
RSpec::Core::RakeTask.new(:spec)

desc "Generate all of the docs"
  YARD::Rake::YardocTask.new do |config|
    config.files = Dir["lib/**/*.rb"]
end 

desc "Default: run tests and generate docs"
task default: [:spec, :yard]


.gitignore

# See http://help.github.com/ignore-files/ for more about ignoring files.
#
# If you find yourself ignoring temporary files generated by your text editor
# or operating system, you probably want to add a global ignore instead:
#   git config --global core.excludesfile ~/.gitignore

# Ignore all of the generated gem stuff
/pkg
/*.gem

# Ignore bundler config
/.bundle
/Gemfile.lock

# Ignore all bundler caching
/vendor/cache
/vendor/ruby

# Ignore all tempfiles
/tmp

# Ignores that should be in the global gitignore
/coverage
/doc

%w

What is the %w “thing” in ruby?

%w means white space divided array


It is a literal, where it is a % then a r(regular expression), w(array), q(string) etc to denote different literals.

$   %w{1 2 3}
 => ["1", "2", "3"]

$   %w[1 2 3]
 => ["1", "2", "3"]

$ %w!a s d f!
 => ["a", "s", "d", "f"]

$ %w@a s d f@
 => ["a", "s", "d", "f"]

So you can see that you can use any character as long as it marks both the beginning and end of the content.

Here are some other examples:

Escape Character List

http://www.java2s.com/Code/Ruby/String/EscapeCharacterslist.htm

backslash hex character
description
/a
0x07
Bell or alert
/b
0x08
Backspace
/cx
--
Control-x
\C-x
--
Control-x
\e
0x1b 
Escape
\f
0x0c
Formfeed
\M-\C-x 
--
Meta-Control-x
\n
0x0a
Newline
\nnn
--
Octal notation, where n is in the range 0-7
\r
0x0d 
Carriage return
\s
0x20
Space
\t
0x09
Tab
\v
0x0b
Vertical tab
\x
--
Character x
\xnn
--
Hexadecimal notation, where n is in the range 0-9, a-f, or A-F

http://www.java2s.com/Code/Ruby/String/Constructastringfromhexvalue.htm

Tuesday, May 13, 2014

Style Guide

Style Guide
name
def
usage
fun example
real world uses
list of all methods
How to Learn
  • random choice
  • in alphabetical order
  • you choose
Size Key
A-small
B-medium
C-Large

pink
#ffff66
#8ae68a#66ccff

Vocabulary - Learn Ruby the Hard Way

ARGV - a global Array variable which holds, as strings, each argument passed by the shell. (The Terminal) The following program iterates over the ARGV array and prints out its contents. In your Ruby programs, you can access any command-line arguments passed by the shell with the ARGV. http://ruby.about.com/od/rubyfeatures/a/argv.htm
#!/usr/bin/env ruby

ARGV.each do|a|
  puts "Argument: #{a}"
end

# The following is an excerpt of a bash session launching this script (saved as the file test.rb) with a variety of arguments.

$ ./test.rb test1 test2 "three four"
Argument: test1
Argument: test2
Argument: three four /div>

A Short explanation of ARGV http://blog.flatironschool.com/post/64043716616/a-short-explanation-of-argv
ARGV.length.size.count

Empty Array http://ruby.about.com/od/rubyfeatures/a/arrayhash.htm
You can create an empty array by creating a new Array object and storing it in a variable. This array will be empty; you must fill it with other variables to use it. This is a common way to create variables if you were to read a list of things from the keyboard or from a file.

In the following example program, an empty array is created using the array command and the assignment operator. Three strings (ordered sequences of characters) are read from the keyboard and "pushed," or added to the end, of the array.

#!/usr/bin/env ruby

array = Array.new

3.times do
  str = gets.chomp
  array.push str
end

File.open

Sinatra

Sinatra Blog Tutorial
This is the tutorial Stephanie used to create our blog for RGSoC

Sinatra Tutorial Links from Tam
http://code.tutsplus.com/tutorials/singing-with-sinatra--net-18965Welcome to Track 1 of "Singing with Sinatra." In this mini-series we'll be taking a look at Sinatra; a small, yet incredibly powerful DSL for quickly creating Ruby web applications. In this part, we'll get started with Sinatra by playing around with a few routes, learning how to access URL parameters and how to POST data between pages.
http://code.tutsplus.com/tutorials/singing-with-sinatra-the-recall-app--net-19128Welcome to Track 2 of Singing with Sinatra.Today, we're going to extend our knowledge of Sinatra by building a small database-driven app, "Recall," for taking notes/making a to-do list.
http://code.tutsplus.com/tutorials/singing-with-sinatra-the-encore--net-19364Welcome back to Singing with Sinatra! In this third and final part we'll be extending the "Recall" app we built in the previous lesson. We're going to add an RSS feed to the app with the incredibly useful Builder gem, which makes creating XML files in Ruby a piece of cake. We'll learn just how easy Sinatra makes escaping HTML from user input to prevent XSS attacks, and we'll improve on some of the error handling code.
Other sites using markdown with sinatra
https://github.com/danmayer/resume 
http://www.danneu.com/posts/15-a-simple-blog-with-sinatra-and-active-record-some-useful-tools/

Git & GitHub


GitHub Video Tutorials

add a  remote origin to your git repo 

Instead of removing and re-adding, you can do this:
  $ git remote set-url origin <git@github.com:whatever.git>

To check your remotes are correct:
  $ git remote -v

newbie notes: 
  • make sure you are in the directory you want to add the remote to and that you are on the master branch
  • don't add the <> brackets, just put the git repo in there ie: git@github.com:whatever.git
  • use the SSH clone URL in the right column of the git repo you want to push and pull from
  • (super newbie note) don't type in the $ sign, this means type this in your terminal


git deleting branches

To delete a local branch
git branch -d the_local_branch

To remove a remote branch (if you know what you are doing!)
git push origin :the_remote_branch

Team TRSL - Fail - TryRuby Upgrade

Turns out that the Spoprinx TryRuby is not the correct TryRuby so no need to upgrade the Rails Version. Boo I was kind of looking forward to that. We may have to build the whole REPL and web app from scratch. Wowza.

Now that I am looking into the Standard Library more it is really huge. I thing we may need to recruit a team from the study group/ Josh said he is interested and maybe we can get Ashook on board. ??

Upgrading TryRuby

Upgrading TryRuby from Rails 3.0.9 to 4.1.1

Monday, May 12, 2014

Definitions of the Ruby Standard Libraries

These are all from:
http://www.ruby-doc.org/core-2.1.1/doc/standard_library_rdoc.html

Libraries 

Abbrev
Calculates a set of unique abbreviations for a given set of strings
Base64
Support for encoding and decoding binary data using a Base64 representation
Benchmark
Provides methods to measure and report the time used to execute code
CGI
Support for the Common Gateway Interface protocol
CMath
Provides Trigonometric and Transcendental functions for complex numbers
complex.rb
Deprecated library replaced by C implementation in core
ConditionVariable
Augments the Mutex class, provided by thread.rb
CSV
Provides an interface to read and write CSV files and data
DEBUGGER__
Debugging functionality for Ruby
Delegator
Provides three abilities to delegate method calls to an object
DRb
Distributed object system for Ruby
E2MM
Module for defining custom exceptions with specific messages
English.rb
Require ‘English.rb’ to reference global variables with less cryptic names
ERB
An easy to use but powerful templating system for Ruby
FileUtils
Several file utility methods for copying, moving, removing, etc
Find
This module supports top-down traversal of a set of file paths
Forwardable
Provides delegation of specified methods to a designated object
GetoptLong
Parse command line options similar to the GNU C getopt_long()
GServer
HTTP server with logging, thread pooling and multi-server management
IPAddr
Provides methods to manipulate IPv4 and IPv6 IP addresses
IRB
Interactive Ruby command-line tool for REPL (Read Eval Print Loop)
Logger
Provides a simple logging utility for outputing messages
mathn.rb
Deprecated library that extends math operations
MakeMakefile
Module used to generate a Makefile for C extensions
Matrix
Represents a mathematical matrix.
MiniTest
A test suite with TDD, BDD, mocking and benchmarking
Monitor
Provides an object or module to use safely by more than one thread
Mutex_m
Mixin to extend objects to be handled like a Mutex
Net::FTP
Support for the File Transfer Protocol
Net::HTTP
HTTP client api for Ruby
Net::IMAP
Ruby client api for Internet Message Access Protocol
Net::POP3
Ruby client library for POP3
Net::SMTP
Simple Mail Transfer Protocol client library for Ruby
Net::Telnet
Telnet client library for Ruby
Observable
Provides a mechanism for publich/subscribe pattern in Ruby
OpenURI
An easy-to-use wrapper for Net::HTTP, Net::HTTPS and Net::FTP
Open3
Provides access to stdin, stdout and stderr when running other programs
OptionParser
Ruby-oriented class for command-line option analysis
OpenStruct
Class to build custom data structures, similar to a Hash
PP
Provides a PrettyPrinter for Ruby objects
PrettyPrinter
Implements a pretty printing algorithm for readable structure
Prime
Prime numbers and factorization library
profile.rb
Runs the Ruby Profiler__
Profiler__
Provides a way to profile your Ruby application
PStore
Implements a file based persistence mechanism based on a Hash
Queue
Synchronized communication between threads, provided by thread.rb
Racc
A LALR(1) parser generator written in Ruby.
Rake
Ruby build program with capabilities similar to make
rational.rb
Deprecated library replaced by C implementation in core
RbConfig
Information of your configure and build of Ruby
RDoc
Produces HTML and command-line documentation for Ruby
resolv-replace.rb
Replace Socket DNS with Resolv
Resolv
Thread-aware DNS resolver library in Ruby
REXML
An XML toolkit for Ruby
Rinda
The Linda distributed computing paradigm in Ruby
RSS
Family of libraries that support various formats of XML “feeds”
Gem
Package management framework for Ruby
Scanf
A Ruby implementation of the C function scanf(3)
SecureRandom
Interface for secure random number generator
Set
Provides a class to deal with collections of unordered, unique values
Shell
An idiomatic Ruby interface for common UNIX shell commands
Shellwords
Manipulates strings with word parsing rules of UNIX Bourne shell
Singleton
Implementation of the Singleton pattern for Ruby
Synchronizer
A module that provides a two-phase lock with a counter
Tempfile
A utility class for managing temporary files
Test::Unit
A compatibility layer for MiniTest
Thread
Provides support classes for threaded programs
ThreadsWait
Watches for termination of multiple threads
Time
Extends the Time class with methods for parsing and conversion
Timeout
Auto-terminate potentially long-running operations in Ruby
tmpdir.rb
Extends the Dir class to manage the OS temporary file path
Tracer
Outputs a source level execution trace of a Ruby program
TSort
Topological sorting using Tarjan’s algorithm
un.rb
Utilities to replace common UNIX commands
URI
A Ruby module providing support for Uniform Resource Identifiers
WeakRef
Allows a referenced object to be garbage-collected
WEBrick
An HTTP server toolkit for Ruby
XMLRPC
Remote Procedure Call over HTTP support for Ruby
YAML
Ruby client library for the Psych YAML implementation

Extensions 

BigDecimal
Provides arbitrary-precision floating point decimal arithmetic
Coverage
Provides coverage measurement for Ruby
Date
A subclass of Object includes Comparable module for handling dates
DateTime
Subclass of Date to handling dates, hours, minutes, seconds, offsets
DBM
Provides a wrapper for the UNIX-style Database Manager Library
Digest
Provides a framework for message digest libraries
DL
Provides a wrapper for the UNIX dlopen() library
Etc
Provides access to information typically stored in UNIX /etc directory
Fcntl
Loads constants defined in the OS fcntl.h C header file
Fiddle
A libffi wrapper for Ruby
GDBM
Ruby extension for the GNU dbm (gdbm) library
IO
Extensions for Ruby IO class, including wait and ::console
JSON
Implements Javascript Object Notation for Ruby
NKF
Ruby extension for Network Kanji Filter
objspace
Extends ObjectSpace module to add methods for internal statistics
OpenSSL
Provides SSL, TSL and general purpose cryptography for Ruby
Pathname
Representation of the name of a file or directory on the filesystem
Psych
A YAML parser and emitter for Ruby
PTY
Creates and manages pseudo terminals
Readline
Provides an interface for GNU Readline and Edit Line (libedit)
Ripper
Provides an interface for parsing Ruby programs into S-expressions
SBDM
Provides a simple file-based key-value store with String keys and values
Socket
Access underlying OS socket implementations
StringIO
Pseudo I/O on String objects
StringScanner
Provides lexical scanning operations on a String
Syslog
Ruby interface for the POSIX system logging facility
Tk
Provides a framework for building a Graphical User Interface (GUI)
WIN32OLE
Provides an interface for OLE Automation in Ruby
Zlib
Ruby interface for the zlib compression/decompression library

The Ruby Standard Library

http://www.ruby-doc.org/core-2.1.1/doc/standard_library_rdoc.html

Ruby Standard Library API

These are the API documents for the standard library classes and modules in version 2.1
The 2.1.1 standard library (this is the current official release)
Additional libraries included with the standard Ruby distribution, such as CGI, OpenURI, and REXML

http://ruby-doc.com/docs/ProgrammingRuby/
Ruby comes ``out of the box'' with a large and useful library of modules and classes. This chapter contains a sampling of the more useful of these.

Interestingly, and unlike some of the code in later chapters, all of these libraries are written in Ruby. You'll find the source in the lib subdirectory of the standard Ruby distribution.

Extracted from the book "Programming Ruby - The Pragmatic Programmer's Guide" 
Copyright © 2001 by Addison Wesley Longman, Inc. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0 or later (the latest version is presently available at http://www.opencontent.org/openpub/)).Distribution of substantively modified versions of this document is prohibited without the explicit permission of the copyright holder.Distribution of the work or derivative of the work in any standard (paper) book form is prohibited unless prior permission is obtained from the copyright holder. 

Thursday, May 8, 2014

Rails Helper Methods

Links to resources:
http://apidock.com/rails/ActionController/Helpers/ClassMethods/helper

Method deprecated or moved
This method is deprecated or moved on the latest stable version. The last existing version (v2.3.8) is shown here.

These similar methods exist in v4.0.2:

AbstractController::Helpers::ClassMethods#helper
Rails::ConsoleMethods#helper

helper(*args, &block) public
The helper class method can take a series of helper module names, a block, or both.
  • *args: One or more modules, strings or symbols, or the special symbol :all.
  • &amp;block: A block defining helper methods.
Examples

When the argument is a string or symbol, the method will provide the "_helper" suffix, require the file and include the module in the template class. The second form illustrates how to include custom helpers when working with namespaced controllers, or other cases where the file containing the helper definition is not in one of Rails' standard load paths:

  helper :foo             # => requires 'foo_helper' and includes FooHelper
  helper 'resources/foo'  # => requires 'resources/foo_helper' and includes Resources::FooHelper
When the argument is a module it will be included directly in the template class.

  helper FooHelper # => includes FooHelper

When the argument is the symbol :all, the controller will include all helpers beneath ActionController::Base.helpers_dir (defaults to app/helpers/*/.rb under RAILS_ROOT).

  helper :all

Additionally, the helper class method can receive and evaluate a block, making the methods defined available to the template.

  # One line
  helper { def hello() "Hello, world!" end }
  # Multi-line
  helper do
    def foo(bar)
      "#{bar} is the very best"
    end
  end
Finally, all the above styles can be mixed together, and the helper method can be invoked with a mix of symbols, strings, modules and blocks.

  helper(:three, BlindHelper) { def mice() 'mice' end }





http://api.rubyonrails.org/classes/ActionController/Helpers.html

Ruby on Rails 4.1.1  Module   ActionController::Helpers
        actionpack/lib/action_controller/metal/helpers.rb

The Rails framework provides a large number of helpers for working with assets, dates, forms, numbers and model objects, to name a few. These helpers are available to all templates by default.
In addition to using the standard template helpers provided, creating custom helpers to extract complicated logic or reusable functionality is strongly encouraged. By default, each controller will include all helpers. These helpers are only accessible on the controller through .helpers

In previous versions of Rails the controller will include a helper whose name matches that of the controller, e.g., MyController will automatically include MyHelper. To return old behavior setconfig.action_controller.include_all_helpers to false.

Additional helpers can be specified using the helper class method in ActionController::Base or any controller which inherits from it.

The to_s method from the Time class can be wrapped in a helper method to display a custom message if a Time object is blank:
module FormattedTimeHelper
  def format_time(time, format=:long, blank_message="&nbsp;")
    time.blank? ? blank_message : time.to_s(format)
  end
end
FormattedTimeHelper can now be included in a controller, using the helper class method:
class EventsController < ActionController::Base
  helper FormattedTimeHelper
  def index
    @events = Event.all
  end
end
Then, in any view rendered by EventController, the format_time method can be called:
<% @events.each do |event| -%>
  <p>
    <%= format_time(event.time, :short, "N/A") %> | <%= event.name %>
  </p>
<% end -%>
Finally, assuming we have two event instances, one which has a time and one which does not, the output might look like this:
23 Aug 11:30 | Carolina Railhawks Soccer Match
N/A | Carolina Railhaws Training Workshop

re:posting this perfectly worded  post about Helper Methods

http://www.oreillynet.com/pub/a/ruby/excerpts/ruby-learning-rails/ruby-catalog-helper-methods.html

A Catalog of Helper Methods: Appendix D - Learning Rails

by Edd Dumbill, Simon St. Laurent
Everyone who has used Rails for a while has their own set of “commonly used” helper methods. Many times, though, those commonly used sets are different. Some people use FormHelper for all of their forms, while others prefer FormTagHelper. Some people use AssetTagHelper, while others handcode links to static resources like stylesheets and images.
Learning Rails book coverThis excerpt is from Learning Rails . Most Rails books are written for programmers looking for information on data structures. Learning Rails targets web developers whose programming experience is tied directly to the Web. Rather than begin with the inner layers of a Rails web application -- the models and controllers -- this unique book approaches Rails development from the outer layer: the application interface. You can start from the foundations of web design you already know, and then move more deeply into Ruby, objects, and database structures.
buy button
Rather than provide a comprehensive reference to these methods—the API documentation does that—this appendix provides a catalog you can browse to decide which methods might actually prove useful to your own needs. Much of the difficulty in using helpers is in finding them before you reinvent the wheel yourself.
All of these classes are subclasses of ActionView::Helpers.

Note

The easiest place to find API documentation, in a friendlier form than usual, is at http://rails-doc.org/. The search boxes give you choices as you type, and the explanations are presented in smaller pieces. You can also find the documentation at http://www.railsbrain.com/ and http://www.gotapi.com/rubyrails. They’re all a little different, but hopefully one of them will prove comfortable for you.

Calling Helper Methods

Every helper method has its own set of parameters, and often it’s not clear from the documentation which parameters it will accept. How do you interpret the following?

label(object_name, method, text = nil, options = {})
The first few parameters at least take simple values. The object_name parameter will take a symbol pointing to an ActiveRecord object, like :person. The method parameter, though—what method does it take? It actually wants a symbol, say :name, for anattribute from the object specified in the previous parameter. Why would the Rails documentation call that a method? Because it’ll use a method to access the attribute.
The next parameter, text, is shown with its default value, nil. Any time you see a parameter listed as equal to something, that value is the default.
And options? What is options? It looks like lots of methods must have the same options, because they all have the same entry in the documentation, but it’s really just a convention. The actual options, named parameters, are listed below in the documentation for the method. Sometimes the options just create HTML attributes—use the name of the attribute to create an attribute, like :id => 'myIDvalue'. Other times the helper methods take more specific options that fit their particular needs. You don’t generally need to surround the options in {}, either.

Note

For more on a case where the curly braces ({}) are necessary, see the section called “Creating Checkboxes” ” in Chapter 6, Presenting Models with Forms.
There’s also a case—with FormHelper methods in particular—where some of the parameters disappear into acontext object. See the section the section called “Form As a Wrapper” ” in Chapter 6, Presenting Models with Forms for more information on how this works.
Sometimes you’ll also see parameters listed that begin with an asterisk, like *sources. This means that you can supply multiple values for that parameter.
Parameters and named parameters are enough for most helper method calls, but every now and then you’ll see a method whose arguments end with &block. form_for is one of the commonly used ones that does this, but some methods take this as an option and others require it. When you call a method with a block, however, the block doesn’t look quite like part of the arguments:

<% benchmark "It took this long:" do %>
  <%= my_long_method %>
<% end % >
In this case, the benchmark method is taking two arguments. The first, a string, is “It took this long:”; this will be text incorporated in the log. The second argument starts with do and closes with end, and includes everything in the middle. That’s the block. (Blocks can also be marked with { and } in normal Ruby code, but in the ERb where you’ll be writing helper methods, do and endare a better choice.)
Because benchmark is keeping track of how long it takes some code to run, it needs that code included as an argument. Thecache, capture, and content_for methods have similar needs, as do form_for and fields_for, which surround a group of methods and provide them context.
For developers coming from less flexible languages, Ruby’s creative use of blocks can be very difficult to figure out. If you’re feeling stuck, your best option is to work from examples until you’re ready to move forward with your own experiments.

ActiveRecordHelper

The ActiveRecordHelper class seems intent on providing the fastest possible path from an ActiveRecord object to an HTML representation. These methods may be useful for putting together very quick demonstrations or for debugging purposes, but they aren’t likely to be your best choice for application-building. (In general, FormHelper and FormTagHelper are better choices for building forms.)
error_message_on
Returns a div containing the error message for a given object and method. You can add text before or after the message.
error_messages_for
Returns a div containing all the error messages for a given object. (The documentation suggests that you look at the code and make your own method if you need something more specific.)
form
Creates a POST-based form based on the ActiveRecord object, all in one call. You can add extra pieces to the form through a block, but mostly this is good for quick-and-dirty instant forms.
input
Creates an input element based on the type of the object and method it’s passed. It’s kind of like a field-by-field version of form.

AssetTagHelper

In Rails terms, an asset is something static that you want to include on a web page that isn’t controlled by Rails. These include things like stylesheets, JavaScript libraries, and sometimes images.
When working on a small scale, assets are stored in the public/ directory of your Rails application, but you can put them on a separate server and tell Rails where to find them through ActionController::Base.asset_host. A separate server can speed delivery, let you share assets with other applications, or just reduce the amount of work your Rails application has to do itself.
The methods in AssetTagHelper will assume files are in your public/ directory unless you’ve specified otherwise. Most of them generate HTML tags for you, though a few let you specify ways to generate tags in the future.
The methods you should probably focus on initially include:
auto_discovery_link_tag
Lets you specify the location of an RSS or Atom feed.
image_tag
Returns an HTML img tag for the specified image name.
javascript_include_tag
Returns a script tag for the JavaScript files you identify as parameters. If one of the parameters is :defaults, theapplication.js file will be included, bringing in the Prototype and Script.aculo.us libraries. You can provide full paths to your scripts, even scripts on other servers, or you can just provide the file’s name. If you’re feeling fancy, you can define groups of styles with register_javascript_expansion, and reference them with symbols.
stylesheet_link_tag
Returns a link tag for the CSS stylesheet files you identify as parameters. You can provide full paths to your stylesheets, even stylesheets on other servers, or you can just provide the name of the file. The :all symbol will link all of the stylesheets in the public/stylesheets directory. As with scripts, if you’re feeling really fancy, you can define groups of styles with register_stylesheet_expansion, and reference them with symbols.
There are other methods in AssetTagHelper, but they’re mostly internal or only used in special cases:
image_path (or path_to_image)
An internal method used to calculate where to point for an image.
javascript_path (or path_to_javascript)
An internal method used to calculate where to point for a JavaScript file.
register_javascript_expansion
Lets you register a symbol that can reference JavaScript files. Useful if you consistently use a group of script files together.
register_javascript_include_default
Lets you add JavaScript files to the :defaults symbol used by the javascript_include_tag method.
register_stylesheet_expansion
Lets you register a symbol that can reference style files. Useful if you consistently use a group of stylesheets together.
stylesheet_path (or path_to_stylesheet)
An internal method used to calculate where to point for a stylesheet.

AtomFeedHelper and AtomFeedHelper::AtomFeedBuilder

Atom feeds started out as more or less the next generation of RSS syndication feeds. RSS can stand for Really Simple Syndication, Rich Site Summary, or RDF Site Summary, which is part of why Atom’s developers decided to start over with a new name. Syndication feeds make it easy for sites, especially news sites and weblogs, to share their content with other websites and consumers, offering a simpler format for articles than full HTML pages. Atom, especially its REST-based Atom Publishing Protocol (AtomPub), has grown beyond just exchanging lists of articles, but Rails’ built-in helper functions focus on fairly traditional feed applications.
AtomHelper is mostly used in Builder templates for creating XML:
atom_feed
Takes a block, creating an atom:feed element and giving the block an AtomFeedBuilder object that child components can use for context. It also accepts parameters for :language, :root_url, :url, and :schema_date.
entry
Creates an atom:entry element. Accepts parameters for :published, which represents the time when the entry was first published, :update, which represents the time of the latest changes, and :url, where to find the entry.
updated
Takes a time and converts it to the right format for Atom feed times.

BenchmarkHelper, CacheHelper, and CaptureHelper

All three of these classes contain methods that wrap around content in your templates. BenchmarkHelper is a class you’ll mostly want to use during development, when it may help you isolate code that’s taking the view a long time to run. CacheHelper andCaptureHelper are both for advanced development. While CacheHelper allows you to specify fragments of your views that will be stored for future reuse, and applied when the same call comes through, CaptureHelper lets you manually grab content that needs to be used again in the same view, probably to share content from the template with the layout:
benchmark
The benchmark method takes an optional message argument and an optional logging level argument (:debug, :info,:warn, or :error). It records how long the wrapped code takes to run. It requires a block argument, so it usually looks something like:

<% benchmark "It took this long:" do %>
 <%= my_long_method %>
<% end % >
The message and the length of time it takes to run will end up in the logs.
cache
The cache method lets you flag fragments of your view to be kept for caching. Like benchmark, cache wraps around the view code it’s meant to work on with a block argument:

<% cache do %>
  <%= my_repetitive_method_that_should_be_cached %>
<% end % >
You should only cache information that doesn’t change very often, but many HTML components are pretty stable.
capture
The capture method wraps around view code and stores its output to a variable. You can then reference the variable and have that content appear wherever you need. In operation, it looks like a variable assignment to a method:

<% @trapped_content = capture do %>
  <%= content_to_put_in_there %>
<% end % >
Once you’ve captured it, you can reference @trapped_content wherever it is convenient.
content_for
The content_for method is much like capture, but instead of putting the content in a variable, it lets you create a named block you can yield to in order to include the content.

DateHelper

The DateHelper class contains two kinds of helper methods. There’s a small set of methods for expressing times in somewhat more human-friendly forms:
distance_of_time_in_words
Takes two time values and expresses how far apart they are in rough word descriptions rather than precise time notation—e.g., “2 days,” or “about 1 month,” or “less than a minute.”
distance_of_time_in_words_to_now or time_ago_in_words
Like distance_of_time_in_words, but with the to_time always set to now.
Most of DateHelper’s methods, though, create form fields for specifying times and dates. They’re kind of clunky, but they may be useful for when you’re getting started or when you feel like overriding them. Three of them are bound to particular objects of type:date, :time, or type :datetime:
date_select
The date_select method creates drop-down year, month, and day select fields bound to a particular ActiveRecord object of type :date.
datetime_select
The datetime_select method creates drop-down year, month, day, hour, minute, and second select fields bound to a particular ActiveRecord object of type :datetime.
time_select
The time_select method creates drop-down hour, minute, and second select fields bound to a particular ActiveRecord object of type :time.
The rest of DateHelper’s methods create HTML form fields, but aren’t bound to any particular ActiveRecord object:
select_date
The select_date method creates drop-down year, month, and day select fields.
select_datetime
The select_datetime method creates drop-down year, month, day, hour, minute, and second select fields.
select_day
The select_day method creates a drop-down field for day of the month (1–31).
select_hour
The select_hour method creates a drop-down field for hours (0–23).
select_minute
The select_minute method creates a drop-down field for minutes (0–59).
select_month
The select_month method creates a drop-down field for month (1–12).
select_second
The select_second method creates a drop-down field for seconds (0–59).
select_time
The select_time method creates drop-down hour, minute, and second select fields.
select_year
The select_year method creates a drop-down field for year. By default it uses five years on either side of the current or selected year, but you can set start and end years through parameters.

DebugHelper

The DebugHelper class isn’t exactly a powerful debugger, but its one method lets you do something that’s often useful in development mode—report an object’s contents:
debug
The debug method takes an object as its argument. It then serializes the object into YAML, and wraps the YAML output (and any errors) in pre tags so you can inspect it.

FormHelper, FormTagHelper, and FormOptionsHelper

These three classes of helper methods offer different approaches to building forms and some different pieces for creating forms. Much of the time you’ll want to use either FormHelper or FormTagHelper, but you might mix FormOptionsHelper with either of the other two.
The FormHelper methods create form fields bound to particular attributes of ActiveRecord objects. They are easiest to use within a form_for method that sets their context, as described in Chapter 6, Presenting Models with Forms. If you don’t like that approach, you can supply an object and attribute name as the first two parameters when calling them. (The documentation for each method shows the parameter approach.)
check_box
Creates a checkbox field bound to an attribute from the object specified in form_for or in the parameters. (It also creates a hidden field bound to the same attribute for use if the checkbox isn’t checked.)
fields_for
fields_for is like form_for, except that it doesn’t create the actual form tags.
file_field
Creates a file upload field bound to an attribute from the object specified in form_for or in the parameters. (You’ll need to modify the form_for call as described in Chapter 8, Improving Forms to use this method.)
form_for
Creates a form element and sets the context for the other helper methods in FormHelper.
hidden_field
Creates a hidden field bound to an attribute from the object specified in form_for or in the parameters.
label
Creates a label for a field created with the other methods of FormHelper.
password_field
Creates a password field bound to an attribute from the object specified in form_for or in the parameters.
radio_button
Creates a radio button bound to an attribute from the object specified in form_for or in the parameters.
text_area
Creates a larger multiline text area bound to an attribute from the object specified in form_for or in the parameters.
text_field
Creates a single-line text field bound to an attribute from the object specified in form_for or in the parameters.
The FormTagHelper class does similar work but provides no automatic binding to a single shared object for a form. It lets you build forms where each component is specified separately:
check_box_tag
Lets you create checkboxes. Unlike check_box, it doesn’t automatically create a hidden field for use if the box is unchecked.
field_set_tag
Creates a fieldset tag for grouping form elements. You can set the legend for the fieldset as an argument.
file_field_tag
Creates a file upload tag. To use this, you also need to give the form_tag method a :multipart => true parameter.
form_tag
Creates a form tag that wraps around other form elements but does not set context like form_for.
hidden_field_tag
Creates a hidden form field.
image_submit_tag
Not for submitting images, but rather for creating submit buttons that are presented as images.
label_tag
Creates a label.
password_field_tag
Creates a password field.
radio_button_tag
Creates a radio button.
select_tag
Creates a drop-down select or multiselect list.
submit_tag
Creates a submit button with a text caption.
text_area_tag
Creates a larger multiline text area.
text_field_tag
Creates a single-line text field.
The FormOptionsHelper methods are complementary to the methods in the other two form-related helper classes. Some of the methods (collection_select, country_select, select, and time_zone_select) take the same arguments as the field-creating methods in FormHelper and can be used the same way, with a context set by form_for or without. The other methods are focused on creating options for those methods, and may also be used to create option lists for the FormTagHelper’sselect_tag method:
collection_select
Creates a select list from a specified object or array.
country_options_for_select
Creates option tags for an alphabetical list of countries, accepting arguments to indicate which should be selected and which should appear first in the list.
country_select
Creates a complete select list of countries including option tags. Also accepts arguments for a selected default and for giving countries higher priority in the list.
option_groups_from_collection_for_select
Creates option tags structured with optgroup tags based on an object or array.
options_for_select
Creates option tags based on a hash or array.
options_from_collection_for_select
Creates option tags based on a collection object.
select
Creates a complete select list including option tags.
time_zone_options_for_select
Returns option tags for time zones across the planet.
time_zone_select
Returns a complete select list for time zones across the planet.

JavaScriptHelper

Sometimes your Rails code will need to generate JavaScript, and not always in the context of RJS, as described in Chapter 16,Creating Dynamic Interfaces with Rails and Ajax. These helper methods make it simpler to add basic JavaScript functionality to your pages, and remove the need to code some kinds of simple JavaScript by hand:
button_to_function
Creates a button that will call a JavaScript function using its onclick handler. It accepts a block of code, which works like RJS.
define_javascript_functions
Creates a link to Prototype and other JavaScript files, but is best avoided. Use javascript_include_tag instead.
escape_javascript
Reformats JavaScript containing carriage returns and quotes so that it can safely be put into HTML attribute values.
javascript_tag
Creates a script tag. Again, javascript_include_tag may be a better option.
link_to_function
Creates a link that will call a JavaScript function. Like button_to_function, it also can take a block that works like RJS.

NumberHelper

The NumberHelper class provides convenience methods for formatting numbers:
number_to_currency
Turns a number into a currency representation. You can select the :unit (denomination), :separator (normally .),:delimiter (normally , ), :format (whether the currency comes before or after the number), and :precision (normally 2).
number_to_human_size
Turns file-size byte counts into more typical human representations, like 12 GB.
number_to_percentage
Turns a number into a percent value. You can select the :precision (normally three digits after the decimal), and the:separator (normally .).
number_to_phone
Turns a number into an American-style telephone number. You can specify a country code, extension, delimiter, and whether or not the area code has parentheses, but you can’t specify how the numbers are broken down.
number_with_delimiter
Formats a number with a given :delimiter between thousands (, by default) and decimal :separator (. by default).
number_with_precision
Formats a number to present as many digits after the decimal point as are specified in the second argument (three is the default).

PrototypeHelper

The Prototype JavaScript library simplifies many common Ajax tasks, but these helper methods make it even more convenient to incorporate calls to Prototype in Rails templates:
evaluate_remote_response
Evaluates the JavaScript response from a remote service using the JavaScript eval method. The eval method opens JavaScript applications up to attack, so be certain that what you’re processing is free of potentially harmful code.
form_remote_for
Same as remote_form_for, described later.
form_remote_tag
Creates a form element that uses an XmlHttpRequest call to submit form data. This allows the page to handle the response rather than reloading an entirely new page.
link_to_remote
Creates a link that issues an XmlHttpRequest call, again allowing the page to handle the response rather than replacing the current page with a new destination.
observe_field
Watches the content of a given field and makes a remote call (or a JavaScript function call) when the content of that field changes. Useful for components like text fields that provide suggestions.
observe_form
Watches the content of a given form and makes a remote call (or a JavaScript function call) when the content of that field changes.
periodically_call_remote
Makes an XmlHttpRequest call every so often, according to a duration specified in seconds set as the :frequency option.
remote_form_for
Works like form_for, except that submitting the form triggers an XmlHttpRequest call that gets handled by Ajax in the browser instead of the usual form submission process.
remote_function
Returns the JavaScript needed to make an XmlHttpRequest call to a remote function.
submit_to_remote
Creates a button that will submit a form using an XmlHttpRequest call.
update_page
Creates the context for RJS calls, allowing a block of code to update multiple elements on the same page.
update_page_tag
Creates JavaScript, wrapped in a script tag, using the same mechanisms as creating RJS code.

RecordIdentificationHelper

These methods make it easier for views to identify components referring to Rails objects when building HTML or RJS:
dom_class
Creates a value suitable for a class attribute that is the singular form of the object name.
dom_id
Creates a value suitable for an id attribute that is the singular form of the object name plus _ and the object’s id value.
partial_path
Creates a value containing plural/singular form of an object’s name, like turtles/turtle or people/person.

SanitizeHelper

The SanitizeHelper methods support a variety of approaches to escaping HTML and CSS. They complement the h method (short for html_escape, part of the ERb:Util class) by providing other approaches to escaping markup or letting it pass:
sanitize
The sanitize method provides a customizable approach to removing attributes and markup that you don’t want to pass through. The customization can be specified through the :tags and :attributes parameters, or set by default through initializer code.
sanitize_css
The sanitize_css method removes features from CSS that the creators of sanitize felt were too dangerous. This is used by sanitize on style attributes.
strip_links
The strip_links method leaves markup other than links intact, but removes all links from the argument.
strip_tags
The strip_tags method removes all HTML markup from the argument. (The documentation warns that it may not always find all HTML markup, however.)

ScriptaculousHelper

Like the PrototypeHelper methods, ScriptaculousHelper methods provide ready Ruby-based access to JavaScript components in the browser. While Prototype focuses on basic Ajax communications, Script.aculo.us focuses more on actions and specialeffects:
draggable_element
Identifies an HTML element, specified by id attribute value, as supporting user efforts to drag it around the screen and potentially drop it on a receiving element.
drop_receiving_element
Identifies an HTML element, again by id attribute value, as a container where users can drop draggable objects and expect a response. When the drop happens, the code this creates can make a remote Ajax call or a local JavaScript call, and supports class-based constraints on which objects to accept. It also supports changing the class of the receiving element to give users visual feedback when they’ve positioned a draggable object over a container that could accept it.
sortable_element
Identifies an HTML element, again by id attribute value, as a collection users can reorder, making an Ajax call when changes occur.
visual_effect
Provides access to the Script.aculo.us library’s collection of visual effects, applying them to an HTML element specified byid.

TagHelper

TagHelper may be of use when you want to create explicit XHTML markup using ERb templates, or want to create view logic that lets the data determine which markup is used. On the one hand, these methods are somewhat obscure; on the other, they may be exactly what you need if clean XHTML is your goal:
cdata_section
As its name suggests, the cdata_section method lets you create CDATA sections wrapping the content specified in the argument. (CDATA sections let you mark sections of an XML document as not containing any markup, so you can use <, >, and & to your heart’s content.)
content_tag
The content_tag method is a generic tag building method. You define the name of the tag, the attributes, and the content of the tag through the arguments.
escape_once
The escape_once method is extremely convenient when you have content that needs <, >, and & escaped—but you might already have done some of the escaping. This method is smart enough to escape markup text that needs escaping, while leaving the ampersands that are part of prior escaping alone.
tag
The tag method creates an empty tag (like <br />).

TextHelper

The TextHelper methods offer a variety of tools for formatting, manipulating, and presenting plain text. If you’re building blogs or other software where users are entering content, this class is worth a close look:
auto_link
The auto_link method is a simple way to make links live without requiring people to use HTML. Its first argument is a block of text. By default, it will turn all URLs and email addresses in that text into live links. The link parameter defaults to:all, but also accepts :email_addresses and :urls as options if you just want one or the other. The href_optionsparameter lets you add attributes.
(If you want to get really fancy, you can supply a block of code that will be executed for every link that gets added, letting you control processing precisely.)
concat
Used for those obscure times when you want to generate output inside of a <% %> ERb code block instead of the usual <%= %> block.
cycle
Creates an object that lets you alternate different values for each member of an array. This lets you do things like alternate formatting to reflect even and odd rows, or mark every 10th element.
excerpt
Finds a given phrase in a given text and returns the phrase with surrounding context.
highlight
Finds a given phrase in a given text and marks all occurrences with <strong class="highlight" >.
markdown
When used with the BlueCloth plug-in (http://www.deveiate.org/projects/BlueCloth), lets you convert text containing Markdown codes (http://daringfireball.net/projects/markdown/syntax) into HTML.
pluralize
Lets you apply Rails’ inflector (the same code that manages singular and plural for ActiveRecord objects) to any text you’d like.
reset_cycle
Starts a cycle (described earlier) over again.
simple_format
Adds HTML line breaks and paragraph marks to plain text.
textilize
When used with the RedCloth plug-in (http://whytheluckystiff.net/ruby/redcloth/), lets you convert text containingTextilize codes (http://www.textism.com/tools/textile) into HTML.
textilize_without_paragraph
Just like textilize, but with one fewer surrounding paragraph mark (<p>...</p>).
truncate
Cuts off the end of a string after a specified number of characters and adds a truncate string, usually ....
word_wrap
Wraps text to a specified line width, breaking on whitespace when possible.

UrlHelper

The UrlHelper class provides methods for creating links inside of your Rails application, letting you take advantage of the routing functionality Rails uses to manage addresses. (And even though the REST world frequently talks about URIs rather than URLs,URLHelper is the place to go to create both.)
button_to
Generates a form containing a single button that links to the specified controller. (It’s the same as url_for, but wraps the result in a button.) You can ask users to confirm their interest after clicking the button.
current_page?
Returns true if the current page has the same URL as the URL created by the options listed.
link_to
Creates a link (a) element linking to the specified controller. (It’s the same as url_for, but wraps the result in an HTML link.)
link_to_if
Like link_to, but lets you specify conditions.
link_to_unless
Like link_to, but lets you specify prohibitions.
link_to_unless_current
Like link_to, but won’t link if the link is to the current page.
mail_to
Creates a mailto: link to a given email address.
url_for
Creates a URL based on the options provided and the Rails application’s routing table.
If you enjoyed this excerpt, buy a copy of Learning Rails .