Posts for: #Snippets

Rails: How To Modify Template Contents Before Rendering

Just a quick snippet to modify template contents before ActionView render them via ERB.

ActionView::Base.class_eval do alias_method :action_view_render_template, :render_template def render_template(template_extension, template, file_path = nil, local_assigns = {}) template ||= read_template_file(file_path, template_extension) template = "
#{template}
" # add your contents here. action_view_render_template(template_extension, template, file_path, local_assigns) end end

You can add this code to environment.rb, but is preferible a plugin.

[]

Rails: How to force plugins loading in 2.0

Sometimes a Rails plugin can be dependant from another one. Since plugins are loaded in alphabetic order, probably you need to load the third part plugin first.

The release 1.2.4 2.0PR introduces breaking changes for this mechanism.

I’m developing a plugin called ClickToGlobalize, that’s dependant on Globalize, here the code for plugin initialization:

# Force Globalize loading. if Rails::VERSION::STRING.match /^1\.2+/ load_plugin(File.join(RAILS_ROOT, 'vendor', 'plugins', 'globalize')) else Rails::Initializer.run { |config| config.plugins = [ :globalize ] } end
require 'click_to_globalize'

Explanation

Use the old mechanism if the current release is minor than the last release with it (1.2.3 1.2.4), else use the Rails::Initializer class.

[]

Ruby: How to check the operating system

Today I’m finishing the code cleanup for my latest Rails plugin (will be soon released) and I want to execute some rake tasks, only if the OS supports certain system calls.

The following snippet helps to check the current platform.

# (c) 2007 Luca Guidi (www.lucaguidi.com) - Released under MIT License. # This code was inspired by Prototype rake test tasks. require 'webrick'
class OperatingSystem
  class  </code>
[]

Ruby on Rails: Validate URL

Hi, just a snippet to validate an url with Ruby on Rails.

class WebSite /^((http|https):\/\/)*[a-z0-9_-]{1,}\.*[a-z0-9_-]{1,}\.[a-z]{2,4}\/*$/i
  def validate
    errors.add(:url, "unexistent") unless WebSite.existent_url?(:url)
  end

  def self.existent_url?(url)
    uri = URI.parse(url)
    http_conn = Net::HTTP.new(uri.host, uri.port)
    resp, data = http_conn.head("/" , nil)
    resp.code == "200"
  end
end
[]

MPlayer console tip

MPlayer tip screenshot I’ve discovered an interesting tip for MPlayer to play all folder’s media files. enter:
mplayer *

It automatically enqueue your files. If you use fast forward (up key) mplayer treats your playlist like one file, so you can navigate between your files. Unfortunately it works only with forward seek.

[]