Skip to content

Instantly share code, notes, and snippets.

View sbellware's full-sized avatar

Scott Bellware sbellware

View GitHub Profile
This code has been moved to a Rails plugin:
http://github.com/sbellware/near-field-errors
@sbellware
sbellware / gist:167002
Created August 13, 2009 05:03
Options to HTML Attributes
def options_to_html_attributes(options)
html_attributes = ""
options.each do |k, v|
html_attributes << "#{k.to_s}=\"#{v}\" "
end
html_attributes.rstrip
end
class FieldError
def self.field_error_proc
Proc.new do |html_tag, error_data|
render_field_with_error html_tag, error_data
end
end
def self.render_field_with_error(html_tag, error_data)
if html_tag =~ /^<label/
return wrap_label_tag_with_label_for_field_with_errors_span(html_tag)
function viewMessages(data) {
this.flashSelector = "div[id='flash']";
if (data) {
this.notice = data.notice;
this.error = data.error;
this.fieldErrors = data.fieldErrors;
if (data.flashSelector) {
this.flashSelector = data.flashSelector;
class Thing
include Composed
has :stuff
has :other_thing, :as => Thing, :expose => ReadWrite
has :one_more_thing, :as => Thing, :ends_with => WebRequest
end
@sbellware
sbellware / tableless_model.rb
Created May 31, 2010 01:13
ActiveRecord model without a backing table. Useful for View Models, and other plain old objects with validations, and other ActiveRecord facilities like associations, etc.
module ViewModel
def self.included(base)
base.extend ClassMethods
base.class_inheritable_accessor :columns
base.columns = []
end
module ClassMethods
def column(name, sql_type = :text, default = nil, null = true)
columns << ActiveRecord::ConnectionAdapters::Column.new(name.to_s, default, sql_type.to_s, null)
@sbellware
sbellware / copyable.rb
Created May 31, 2010 01:39
Copy ActiveRecord model values to another model
module Copyable
attr_writer :copyable_attributes
def copyable_attributes
@copyable_attributes ||= attributes.keys.reject { |k, v| k.to_s =~ /^id$|_id$|^created_at$|^updated_at$/ }
end
def copy(options={})
class_sym = options.delete :class
other = options.delete :other
@sbellware
sbellware / anon_class.rb
Created June 29, 2010 21:46
Create an anonymous class from a hash
def data_transfer_object(options)
Class.new do
def initialize(options)
options.each do |key, value|
instance_variable_set("@#{key}", value)
end
end
options.each do |key, value|
define_method key do
@sbellware
sbellware / require_dir.rb
Created June 30, 2010 21:19
Require .rb files in a directory
file_spec = File.expand_path(File.join(File.dirname(__FILE__), 'some_dir', '*.rb'))
Dir[file_spec].each do |file|
required = file.gsub('.rb', '')
require required
end
class Hash
def prepend(value, key)
aditional_value = delete(key)
merge! key => "#{value} #{aditional_value}".rstrip
end
end