Created
October 4, 2011 13:28
-
-
Save edtsech/1261642 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 = '[email protected]' | |
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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