Module: Camping::Helpers

Included in:
Controllers::Base, Views
Defined in:
lib/camping-unabridged.rb,
lib/camping.rb

Overview

Helpers contains methods available in your controllers and views. You may add methods of your own to this module, including many helper methods from Rails. This is analogous to Rails’ ApplicationHelper module.

Using ActionPack Helpers

If you’d like to include helpers from Rails’ modules, you’ll need to look up the helper module in the Rails documentation at api.rubyonrails.org/.

For example, if you look up the ActionView::Helpers::FormHelper class, you’ll find that it’s loaded from the action_view/helpers/form_helper.rb file. You’ll need to have the ActionPack gem installed for this to work.

require 'action_view/helpers/form_helper.rb'

# This example is unfinished.. soon..

Instance Method Summary collapse

Instance Method Details

#/(p) ⇒ Object

Simply builds the complete URL from a relative or absolute path p. If your application is running from /blog:

self / "/view/1"    #=> "/blog/view/1"
self / "styles.css" #=> "styles.css"
self / R(Edit, 1)   #=> "/blog/edit/1"


199
# File 'lib/camping-unabridged.rb', line 199

def / p;p[/^\//]?@root+p:p end

#errors_for(o) ⇒ Object

Shows AR validation errors for the object passed. There is no output if there are no errors.

An example might look like:

errors_for @post

Might (depending on actual data) render something like this in Markaby:

ul.errors do
  li "Body can't be empty"
  li "Title must be unique"
end

Add a simple ul.errors font-weight:bold; CSS rule and you have built-in, usable error checking in only one line of code. :-)

See AR validation documentation for details on validations.



191
192
# File 'lib/camping-unabridged.rb', line 191

def errors_for(o);ul.errors{o.
errors.each_full{|er|li er}}unless o.errors.empty?;end

#R(c, *args) ⇒ Object

From inside your controllers and views, you will often need to figure out the route used to get to a certain controller c. Pass the controller class and any arguments into the R method, a string containing the route will be returned to you.

Assuming you have a specific route in an edit controller:

class Edit < R '/edit/(\d+)'

A specific route to the Edit controller can be built with:

R(Edit, 1)

Which outputs: /edit/1.

You may also pass in a model object and the ID of the object will be used.

If a controller has many routes, the route will be selected if it is the first in the routing list to have the right number of arguments.

Keep in mind that this route doesn’t include the root path. Occassionally you will need to use / (the slash method above).



167
168
169
# File 'lib/camping-unabridged.rb', line 167

def R c,*args;p=/\(.+?\)/;args.inject(c.urls.find{|x|x.scan(p
).size==args.size}.dup){|str,a|str.sub(p,(a.__send__(a.class.primary_key)rescue
a).to_s)};end