Skip to content

Instantly share code, notes, and snippets.

@caleon
caleon / core_utilities.rb
Created August 29, 2011 12:16
Some of my favorite core extensions for Ruby and Rails used on practically all of my projects these days
# This file meant for globally available, utility methods.
###############################
## Ruby-level Extensions ##
###############################
class Object
def as(&block)
yield self
end
@caleon
caleon / string_grouped_inquirer.rb
Created August 29, 2011 12:20
An extension of ActiveSupport::StringInquirer to have a grouping of environments such that Rails.env.live? checks if the environment is either production OR staging, and Rails.env.trial? to check that the env is neither of those.
class RailsEnvInquirer < ActiveSupport::StringInquirer
def live?
%w(production staging).include?(self)
end
def trial?
!live?
end
def grouping
@caleon
caleon / active record error on field test.rb
Created October 20, 2011 11:55
Rails ActiveSupport::TestCase helper method for checking a model record has an error on a field
# This method allows you to not have to hardcode validation messages as a part of unit
# tests, instead relying, as the ActiveModel::Errors class does, on I18n dictionaries.
# Usage: assert_has_error(@new_user, :first_name, :regexp)
# Of course, in the above example, :regexp is a custom type of error that I implemented
# for my own app, but you can substitute things like :invalid, :blank, :inclusion, etc.
def assert_has_error(record, attribute, type = :invalid)
record.send(:run_validations!) # This in order to trigger the :validate callback first.
assert record.errors[attribute].include?(record.errors.generate_message(attribute, type)), "Expected #{record.class.model_name.human} record to have an error of type :#{type} for attribute #{record.class.human_attribute_name(attribute)}."
end
@caleon
caleon / new_inflection_generator_for_rails.rb
Created February 15, 2012 11:42
Simple creation of new inflections in Rails 3 (or whatever uses ActiveSupport::Inflector)
# In case you want to define a new inflection so you can call something like:
#
# "masochistic son of a gun".leet # => "m450ch1571c 50n 0f 4 9un"
#
# Do the following so that the requisite methods are injected into each relevant
# class/module:
#
# NewInflection.register :leet do |word|
# word.tr('aegilost', '43911057')
# end