Created
May 9, 2012 09:57
-
-
Save jhbabon/2643476 to your computer and use it in GitHub Desktop.
Useful Rails 2.3 view helpers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # -*- encoding: utf-8 -*- | |
| module ApplicationHelper | |
| def title(txt, show = true) | |
| content_for(:title) { h(txt.to_s) } | |
| @show_title = show | |
| show_title | |
| end | |
| def show_title? | |
| @show_title | |
| end | |
| def show_title(&block) | |
| if show_title? | |
| block_given? ? concat(capture(&block)) : yield_or(:title, '') | |
| end | |
| end | |
| def page_title | |
| yield_or(:title, I18n.t('application.defaults.title')) | |
| end | |
| def description(txt) | |
| content_for(:description) { h(txt.to_s) } | |
| end | |
| def page_description | |
| yield_or(:description, I18n.t('application.defaults.title')) | |
| end | |
| def header | |
| render :partial => 'shared/header' | |
| end | |
| def footer | |
| render :partial => 'shared/footer' | |
| end | |
| # Asynchronous Google Analytics snippet. | |
| # link: mathiasbynens.be/notes/async-analytics-snippet | |
| def google_analytics_snippet | |
| google_id = 'UA-XXXXX-X' # get from app preferences | |
| unless google_id.blank? | |
| snippet = [ | |
| "var _gaq=[['_setAccount','#{google_id}'],['_trackPageview']]", | |
| "(function(d,t){var g=d.createElement(t),s=d.getElementsByTagName(t)[0]", | |
| "g.src=('https:'==location.protocol?'//ssl':'//www')+'.google-analytics.com/ga.js'", | |
| "s.parentNode.insertBefore(g,s)}(document,'script'))", | |
| ] | |
| javascript_tag { snippet.map { |line| "#{line};\n" }.reduce(:+) } | |
| end | |
| end | |
| # Get the value of a content_for block or fallback to the content | |
| # or block given | |
| # @link: http://stackoverflow.com/a/5238497 | |
| def yield_or(name, content = nil, &block) | |
| ivar = "@content_for_#{name}" | |
| if instance_variable_defined?(ivar) | |
| content = instance_variable_get(ivar) | |
| else | |
| content = block_given? ? capture(&block) : content | |
| end | |
| block_given? ? concat(content) : content | |
| end | |
| end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment