Skip to content

Instantly share code, notes, and snippets.

@edtsech
Created October 4, 2011 13:28
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save edtsech/1261642 to your computer and use it in GitHub Desktop.
Save edtsech/1261642 to your computer and use it in GitHub Desktop.
Gem::Specification.new do |s|
s.name = 'acts_as_untitled'
s.version = '0.1.0'
s.platform = Gem::Platform::RUBY
s.author = 'Edward Tsech'
s.email = 'edtsech@gmail.com'
s.summary = 'Acts as untitled!'
s.description = ''
s.files = ['acts_as_untitled.rb']
s.test_file = 'acts_as_untitled_test.rb'
s.require_path = '.'
end
module ActiveRecord
module Acts
module Untitled
extend ActiveSupport::Concern
module ClassMethods
def acts_as_untitled(attr = :title, placeholder = nil)
placeholder ||= 'Untitled #{self.class.to_s.downcase}'
class_eval <<-EOV
before_save lambda {
self.send(:#{attr}=, "#{placeholder}") unless self.send(:#{attr}).present?
}
EOV
end
end
end
end
end
ActiveRecord::Base.class_eval { include ActiveRecord::Acts::Untitled }
require 'rubygems'
require 'active_record'
require 'test/unit'
require File.expand_path('acts_as_untitled')
# The database
ActiveRecord::Base.establish_connection(:adapter => "sqlite3", :database => ":memory:")
ActiveRecord::Schema.define(:version => 1) do
create_table :posts do |t|
t.string :title
end
create_table :projects do |t|
t.string :name
end
create_table :items do |t|
t.string :name
end
end
# Models
class Post < ActiveRecord::Base
acts_as_untitled
end
class Project < ActiveRecord::Base
acts_as_untitled :name
end
class Item < ActiveRecord::Base
acts_as_untitled :name, "Blah blah"
end
# Tests
class ActsAsUntitledTest < Test::Unit::TestCase
def test_acts_as_untitled
assert_equal Post.create.title, 'Untitled post'
end
def test_acts_as_untitled_with_custom_attr
assert_equal Project.create.name, 'Untitled project'
end
def test_acts_as_untitled_with_placeholder
assert_equal Item.create.name, 'Blah blah'
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment