Skip to content

Instantly share code, notes, and snippets.

View ismasan's full-sized avatar

Ismael Celis ismasan

View GitHub Profile
# Create ActiveRecord schemas on the fly for AR extensions testing
#
ActiveRecord::Base.establish_connection(
:adapter=>'sqlite3',
:dbfile=> File.join(File.dirname(__FILE__),'..','spec','db','test.db')
)
# define a migration
class TestSchema < ActiveRecord::Migration
def self.up
create_table :items do |t|
module BlahPlugin
VERSION = '1.0.0'
class << self
# add plugin to AR only if it hasn't been included before,
# which may cause stack-level-too-deep errors if you're aliasing methods
#
def enable_activerecord
return if ActiveRecord::Base.respond_to? :acts_as_blah
ActiveRecord::Base.extend BlahPlugin::Macro
# we want /posts, /posts/published, /posts/drafts, etc. without too much duplication
# model
class Post < ActiveRecord::Base
named_scope :published, lambda {{:conditions => ...}}
named_scope :draft, lambda {{:conditions => ...}}
named_scope :expired, lambda {{:conditions => ...}}
named_scope :upcoming, lambda {{:conditions => ...}}
end
# Easy ActiveRecord sorting with named_scopes and resources_controller
# this goes in your initializers, lib directory or as a plugin
module ClassMethods
def sortable_with(*fields)
sorts = fields.inject({}) do |h,f|
h[:"#{f}_asc"] = "#{f} ASC"
h[:"#{f}_desc"] = "#{f} DESC"
h
end
write_inheritable_attribute(:sortable_fields,sorts)
# this facades a model with all helpers and controller data available
#
class RssModel
def initialize(model, request, controller)
@model, @request, @controller = model, request, controller
end
# you have request available as well
#
module Spec
module Rails
module Matchers
def have_sane_through_associations
return simple_matcher(":through associations not to have the :dependent options}") do |model|
model = model.class if model.is_a? ActiveRecord::Base
not model.reflect_on_all_associations.any?{|a| a.options[:through] && a.options[:dependent]}
end
end
class Post < ActiveRecord::Base
belongs_to :user
belongs_to :shop
named_scope :by_author, lambda {|user_id|
return {} if user_id.blank?
{:conditions => {:user_id => user_id}}
}
named_scope :like, lambda {|q|
# Put this in an initializer (config/initializers/common_scopes.rb) or library file.
#
module CommonScopes
module ClassMethods
# Sort given fields ASC or DESC
#
# Example:
#
# class Post < ActiveRecord::Base
# Cache Headers
# Middleware for configuring HTTP cache policy headers in Rack based web applications.
# Apply cache headers to HTTP responses corresponding to requests that match defined
# URI patterns.
#
# Example usage:
#
# use Rack::CacheHeaders
#
# Rack::CacheHeaders.configure do |cache|
class ManyLevels
extend HashMapper
map from('/name'), to('/tag_attributes/name')
map from('/properties/type'), to('/tag_attributes/type')
map from('/tagid'), to('/tag_id')
map from('/properties/egg'), to('/chicken')
end
input = {
:name => 'ismael',