module I18n::Backend class Simple protected def pluralize(locale, entry, count) return entry unless entry.is_a?(Hash) and count key = :zero if count == 0 && entry.has_key?(:zero) key ||= count == 1 ? :one : (2..4).include?(count) ? :few : :other raise InvalidPluralizationData.new(entry, count) unless entry.has_key?(key) entry[key] end end # class end # module
Category: ruby/rails
normalize UTF8 (translit/deaccent)
place this in your application.rb (eg)
class String def translit Unicode.normalize_KD(self).unpack('U*').select{ |cp| cp < 127 }.pack('U*').gsub(/ /,'-').downcase end end
Rails 2.1.0 – named_scope
New version of rails comes with a great feature called named_scope.
# in your model.rb
class Model < ActiveRecord::Base has_many ... belongs_to ... named_scope :active, :conditions => {:state => 'active'} named_scope :today, :conditions => ['date_created between ? and ?', Time.today.to_i, Time.today.to_i+3600*24-1] named_scope :by_date_asc, :order => 'date_created asc' named_scope :by_date_desc, :order => 'date_created desc' named_scope :user_name, lambda {|name| {:conditions => {:username => name}}
and you can use its as:
# somewhere in your code
@data = Model.today @data = Model.today.active.by_date_asc @data = Model.user_name('some user').active.today.by_date_desc
own application configuration
./config/my_configuration.yml
MyConfig: username: my_username password: my_password host: my_host
be sure to enter spaces, NOT tabs
./config/environment.rb
require 'ostruct' require 'yaml' OwnConfigFile = "#{RAILS_ROOT}/config/my_configuration.yml" if File.exist?(MyConfigFile) ::ApplicationConfig = OpenStruct.new(YAML.load_file(MyConfigFile)) end
in application:
config = ApplicationConfig.MyConfig; puts config['username']
Exception handling
./lib/mymodule.rb module MyModule class Error < RuntimeError; end class ConnectionError < Error; end def connect if something_failed? raise ConnectionError, "connection failed due to..." end end end
somewhere in controller
include MyModule def do_connect begin connect rescue MyModule::ConnectionError => err flash.now[:notice] => err end end
Retrieving user login/pass from HTTP_AUTH*
I’m using this to get login information from mod_ldap_auth – user is authenticated against Microsoft’s Active Directory (AD)
def getAuthenticated if request.env['HTTP_AUTHORIZATION'] then authdata = request.env['HTTP_AUTHORIZATION'].to_s.split user,pass = Base64.decode64(authdata[1]).split(':')[0..1] [ user, pass ] else [ "", "" ] end end
Using GOOGLE API (WSDL example)
def search require 'soap/wsdlDriver' @title = 'Search Results' key = 'YOUR GOOGLE API KEY HERE' yoursite = 'YOUR SITE ADDRESS HERE' driver = SOAP::WSDLDriverFactory.new("http://api.google.com/GoogleSearch.wsdl").createDriver @results = driver.doGoogleSearch(key, @params['term']+" site:#{yoursite}", 0, 10, true, " ", false, " ", " ", " ") end
and parsing data
<% for result in @results.resultElements %> <%= result.title %> <%= result.snippet %> <%= result.URL %> <% end %>