Posts for: #Ruby

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>
[]

Play random files with Ruby

I’ve written a class to play random files, you can define the player path and allowed file extentions. It will search recursively for all readable files, starting from execution from the folder passed as argument or, if miss, from current folder. Tested on a linux box with mplayer.

Usage:
$ ./shuffle # play recursively all files from current folder $ ./shuffle /path/to/files # play recursively all files from specified folder

That’s the source code.
#!/usr/bin/ruby

[]

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
[]